Hi,
I have a parameterized class :
class ParameterizedClass<T extends AbstractSomething> { }
calling:
new ParameterizedClass<Something>();
So how can I get actual type Something of T by using Java Generics?
Hi,
I have a parameterized class :
class ParameterizedClass<T extends AbstractSomething> { }
calling:
new ParameterizedClass<Something>();
So how can I get actual type Something of T by using Java Generics?
You could 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 this code only works when the class is sub-classed and an instance of the sub-class executes it.
If you mean just from the object itself, you can't. Type erasure means that information is lost.
If you have a field which uses the parameterized type with a concrete type argument though, that information is preserved.
See Angelika Langer's Generics FAQ, and particularly the section on type erasure.
Due to type erasure, this isn't possible in Java, unfortunately.
What I recommend in these circumstances, is to create a class 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's type inference for static methods, you can construct your class without too much extra boilerplate:
ParameterizedClass<Something> foo = ParameterizedClass.of(Something.class);
That way, your ParameterizedClass
is fully generic and type-safe, and you still have access to the class object.
This is a mostly problematic topic, since it only works under certain conditions like expected (expecially in complex scenarios).
But Xebia published a good article on the whole thing.