I have an abstract class Abstr<T> and an extending class Ext<T>. I need Abstr to know, with which T its extension was initialized so it can return that type. So far I’ve done this by giving the type to the constructor and then calling the superconstructor to save it. But this should work with reflections too I think. So far like I said:
public abstract class Abstr<T> {
private Class<T> type;
public Abstr(Class<T> _class) {
this.type = _class;
}
}
public class Ext<T> extends Abstr<T> {
public Ext(Class<T> _class) {
super(_class);
}
}
public void someMethod() {
Ext<String> ext = new Ext<String>(String.class);
}
Using reflections should rid me of calling any constructor as the extending default constructor will call the abstract classes default constructor which should then save the type of the calling constructor:
public Abstr() {
this.type = (Class<D>) this.getClass().getTheTypeParameter(); // something along these lines
}
Thanks!
If you really need a method in
Abstrsimilar toyou have no choice but to pass the
Classisntance in the constructor (or in any other method). You cannot retrieve theClassofTdue to type erasure, which basically comes down to the fact thatTis not available at runtime, only at compile time.