Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get a class instance of generic type T?

Tags:

java

generics

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?

like image 483
robinmag Avatar asked Aug 09 '10 06:08

robinmag


People also ask

How do I find the instance of a generic type?

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.

How do you create an instance of a generic class in Java?

To update the Box class to use generics, you create a generic type declaration by changing the code "public class Box" to "public class Box<T>". This introduces the type variable, T, that can be used anywhere inside the class. As you can see, all occurrences of Object are replaced by T.

Can you create instances of generic type parameters?

Cannot Instantiate Generic Types with Primitive Types. Cannot Create Instances of Type Parameters.


1 Answers

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.

class Foo<T> {     final Class<T> typeParameterClass;      public Foo(Class<T> typeParameterClass) {         this.typeParameterClass = typeParameterClass;     }      public void bar() {         // you can access the typeParameterClass here and do whatever you like     } } 
like image 123
Zsolt Török Avatar answered Oct 19 '22 10:10

Zsolt Török