I have a generics class, Foo<T>
. In a method of Foo
, I want to get the class instance of type T, but I just can't call T.class
.
What is the preferred way to get around it using T.class
?
I have a generics class, Foo<T>
. In a method of Foo
, I want to get the class instance of type T, but I just can't call T.class
.
What is the preferred way to get around it using T.class
?
Here is a working solution:
NOTES: Can be used only as superclass
Child extends Generic<Integer>
)OR
new Generic<Integer>() {};
)There is a small loophole however: if you define your
Foo
class as abstract. That would mean you have to instantiate you class as:(Note the double braces at the end.)
Now you can retrieve the type of
T
at runtime:Note however that
mySuperclass
has to be the superclass of the class definition actually defining the final type forT
.It is also not very elegant, but you have to decide whether you prefer
new Foo<MyType>(){}
ornew Foo<MyType>(MyType.class);
in your code.For example:
Then:
Imagine you have an abstract superclass that is generic:
And then you have a second class that extends Foo with a generic Bar that extends T:
You can get the class
Bar.class
in the Foo class by selecting theType
(from bert bruynooghe answer) and infering it usingClass
instance:You have to note this operation is not ideal, so it is a good idea to cache the computed value to avoid multiple calculations on this. One of the typical uses is in generic DAO implementation.
The final implementation:
The value returned is Bar.class when invoked from Foo class in other function or from Bar class.
I have an (ugly but effective) solution for this problem, which I used recently: