Back

Explore Courses Blog Tutorials Interview Questions
0 votes
3 views
in Java by (3.4k points)

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?

1 Answer

0 votes
by (46k points)

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

    }

}

Browse Categories

...