How can I find out the actual type argument for a generic class?

I have a parameterized class:

class ParameterizedClass<T extends AbstractSomething> { } 

vocation:

 new ParameterizedClass<Something>(); 

So, how can I get the actual Something type from T using Java Generics?

+6
java generics reflection
source share
4 answers

It can be done, but type erasure can make it very difficult. Like the other answers, you either have to subclass ParameterizedClass , or add a field of type T to ParameterizedClass , and the reflection code you need to do is collapsed.

What I recommend in these circumstances is to work around the problem as follows:

 class ParameterizedClass<T> { private Class<T> type; /** Factory method */ public static <T> ParameterizedClass<T> of(Class<T> type) { return new ParameterizedClass<T>(type); } /** Private constructor; use the factory method instead */ private ParameterizedClass(Class<T> type) { this.type = type; } // Do something useful with type } 

Due to Java type inference for static methods, you can create your class without an extra template:

 ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class); 

Thus, your ParameterizedClass fully versatile and type safe, and you still have access to the class object.

EDIT : Comment Address

+9
source share

You can use this trick in your constructor: (see http://www.hibernate.org/328.html )

 Class<T> parameterType = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0]; 

But I believe that this code only works when the class is subclassed and an instance of the subclass executes it.

+8
source share

If you mean only from the object itself, you cannot. The type of erasure means that information is lost.

If you have a field that uses a parameterized type with an argument of a specific type, this information is saved.

See the Angelics Langer Generics Frequently Asked Questions , and in particular the erase type section.

+3
source share

This is the most problematic topic since it only works under certain conditions (for example, in complex scenarios).

But Xebia posted a good article overall.

0
source share

All Articles