Re: Get the parameterized type of a subclass
cdvr wrote:
public abstract class AbstractFoo<T> implements Foo<T> {
public void printParamType() {
// print the actual type of T
Class subclass = getClass();
for(Class c; (c = subclass.getSuperclass())
!= AbstractFoo.class; subclass = c);
ParameterizedType type = (ParameterizedType)
subclass.getGenericSuperclass();
System.out.println(type.getActualTypeArguments()[0]);
}
}
public class MyFoo extends AbstractFoo<Blah> {
public void static main(String[] args) {
MyFoo f = new MyFoo();
f.printParamType();
}
}
What I'd like to get is the type "Blah"....how can I get that Type or
reference to the Class object at run-time?
The sample code above shows how to do that. It assumes that you pass an
actual type directly from the superclass (as in a case of your MyFoo
class). However, in general, it may be more complex (e.g. actual type
passed from non direct subclass), or even impossible to infer what the
actual type argument type is (type erasure). BTW -- Maybe the later
limitation will become weaker soon, thanks to the Neal Gafter proposal
of making generic types fully reifiable.
piotr