Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class reference for a Java inner class

Is there a way to refer to any inner class?

I would like to specify a return type compatible with an inner class e.g.

Class<OuterClass.*> some_method();

I understand this syntax is invalid. Is there a way to express this?

I know I can't use something like Class<? extends OuterClass> because an inner class doesn't extend an outer class.

like image 570
jldupont Avatar asked Aug 22 '12 11:08

jldupont


2 Answers

Well, you can refer to specific inner classes, at least:

<T extends OuterClass.InnerClass> Class<T> some_method()

Besides that, what would you gain by returning an object of any inner class? That would be comparable to returning any object plus the fact that the inner instance has a special relation to the outer instance. However, you'd probably not be able to directly use that special relation anyways.

Edit:

As others pointed out already InnerClass might be a super class extended by other inner classes. This would allow you to return any class, that extends that class.

If you'd use an interface, you aren't restricted to inner classes only, since for this restriction you'd need non-static inner interfaces. However, inner interfaces are static by default.

like image 54
Thomas Avatar answered Sep 30 '22 10:09

Thomas


I would rather define an (inner) interface, let all inner class implement it, and then :

Class<OuterClass.MyInterface> someMethod();

This would be more type secure than trying to refer to any inner class. And you wouldn't have any problem the day you need another inner class for another usage, or the day you decide to extract a class.

like image 43
Denys Séguret Avatar answered Sep 30 '22 11:09

Denys Séguret