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
?
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
?
Actually, I suppose you have a field in your class of type T. If there's no field of type T, what's the point of having a generic Type? So, you can simply do an instanceof on that field.
In my case, I have a
in my class, and I check if the class type is "Locality" byOf course, this only works if the total number of possible classes is limited.
I'm using workaround for this:
I was looking for a way to do this myself without adding an extra dependency to the classpath. After some investigation I found that it is possible as long as you have a generic supertype. This was OK for me as I was working with a DAO layer with a generic layer supertype. If this fits your scenario then it's the neatest approach IMHO.
Most generics use cases I've come across have some kind of generic supertype e.g.
List<T>
forArrayList<T>
orGenericDAO<T>
forDAO<T>
, etc.Pure Java solution
The article Accessing generic types at runtime in Java explains how you can do it using pure Java.
Spring solution
My project was using Spring which is even better as Spring has a handy utility method for finding the type. This is the best approach for me as it looks neatest. I guess if you weren't using Spring you could write your own utility method.
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.I had this problem in an abstract generic class. In this particular case, the solution is simpler:
and later on the derived class:
It's possible:
You need two functions from svn/trunk/dao/src/main/java/com/googlecode/genericdao/dao/ DAOUtil.java.
For more explanations, see Reflecting generics.