Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the class of type variable in Java Generics

Tags:

I've seen similar questions but they didnt help very much.

For instance I've got this Generic Class:

public class ContainerTest<T> {      public void doSomething()     {         //I want here to determinate the Class of the type argument (In this case String)     } } 

and Another Class which uses this Container Class

public class TestCase {      private ContainerTest<String> containerTest;      public void someMethod()     {         containerTest.doSomething();     } } 

Is it possible to determinate the Class of the type argument in method doSomething() without having an explicit type variable/field or any constructor in ContainerTest Class?

Update: Changed format of ContainerTest Class

like image 579
ZeDonDino Avatar asked Feb 26 '13 08:02

ZeDonDino


People also ask

How do you find the class object of a generic type?

Pass the class object instead and it's easy. The idea here is that since you can't extract the type parameter from the object, you have to do it the other way around: start with the class and then manipulate the object to match the type parameter. Show activity on this post. Show activity on this post.

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

The short answer is, that there is no way to find out the runtime type of generic type parameters in Java. A solution to this is to pass the Class of the type parameter into the constructor of the generic type, e.g.

How do you find the class of a variable in Java?

Use getClass(). getSimpleName() to Check the Type of a Variable in Java. We can check the type of a variable in Java by calling getClass(). getSimpleName() method via the variable.

What is the generic class type called?

Generic Classes These classes are known as parameterized classes or parameterized types because they accept one or more parameters.


1 Answers

The only way is to store the class in an instance variable and require it as an argument of the constructor:

public class ContainerTest<T> {     private Class<T> tClass;     public ContainerTest(Class<T> tClass) {         this.tCLass = tClass;     }      public void doSomething()     {         //access tClass here     } } 
like image 50
Didier L Avatar answered Sep 30 '22 21:09

Didier L