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
?
genericsjava
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
?
Best Answer
The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. I suggest reading the chapter about type erasure in the Java Tutorial for more details.
A popular solution to this is to pass the
Class
of the type parameter into the constructor of the generic type, e.g.