Re: Get the parameterized type of a subclass
On Jul 21, 12:08 pm, cdvr <codecr...@gmail.com> wrote:
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?
public interface Foo<T> { ... }
public abstract class AbstractFoo<T> implements Foo<T> {
private Class<T> paramType;
protected AbstractFoo (Class<T> paramType) {
this.paramType = paramType;
}
public void printParamType() {
System.out.println(paramType);
}
}
public class MyFoo extends AbstractFoo<Blah> {
public MyFoo () {
super(Blah.class);
}
public void static main(String[] args) {
MyFoo f = new MyFoo();
f.printParamType();
}
}
You might want to specify printParamType in the interface, or better
yet make it getParamType and leave it up to the caller what to do with
the Class object. Of course the param type class object has to be
passed to the AbstractFoo constructor by its subclasses. Any instance
can be queried regarding the param type. Subtypes that are still
parametrized can continue to ask for it in their constructors to pass
to the superclass constructor; ones that are not parametrized,
extending Superclass<SpecificType>, can call super(SpecificType.class)
in their constructors.