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
?
I found a generic and simple way to do that. In my class I created a method that returns the generic type according to it's position in the class definition. Let's assume a class definition like this:
Now let's create some attributes to persist the types:
Then you can create a generic method that returns the type based on the index of the generic definition:
Finally, in the constructor just call the method and send the index for each type. The complete code should look like:
If you are extending or implementing any class/interface that are using generics , you may get the Generic Type of parent class/interface, without modifying any existing class/interface at all.
There could be three possibilities,
Case 1 When your class is extending a class that is using Generics
Case 2 When your class is implementing an interface that is using Generics
Case 3 When your interface is extending an interface that is using Generics
You can't do it because of type erasure. See also Stack Overflow question Java generics - type erasure - when and what happens.
A better route than the Class the others suggested is to pass in an object that can do what you would have done with the Class, e.g., create a new instance.
A standard approach/workaround/solution is to add a
class
object to the constructor(s), like:As explained in other answers, to use this
ParameterizedType
approach, you need to extend the class, but that seems like extra work to make a whole new class that extends it...So, making the class abstract it forces you to extend it, thus satisfying the subclassing requirement. (using lombok's @Getter).
Now to extend it without defining a new class. (Note the {} on the end... extended, but don't overwrite anything - unless you want to).