Back
I have a generics class, Foo<T>. In a method of Foo, I want to get the class example of type T, but I just can't call T.class.
What is the favored way to get around it using T.class?
There is no method to find out the runtime model of generic type parameters in Java. Go through this document more details.
You can pass the Class of the type parameter into the constructor of the generic type to solve this problem, Example:
class Foo<T> { final Class<T> typeParameterClass; public Foo(Class<T> typeParameterClass) { this.typeParameterClass = typeParameterClass; } public void bar() { // access the typeParameterClass here and do your stuff }}
class Foo<T> {
final Class<T> typeParameterClass;
public Foo(Class<T> typeParameterClass) {
this.typeParameterClass = typeParameterClass;
}
public void bar() {
// access the typeParameterClass here and do your stuff
31k questions
32.8k answers
501 comments
693 users