I have a generic class with a method that calls another method that requires a class object as one of its arguments. I would like to be able to use the class type that's set as the generic at object creation time but I can't quite seem to get the syntax right. Here's what I would like to do:
public abstract class GenericClass<T> {
private void doStuff() {
//do a bunch of stuff
//This method's signature is methodToCall(Serializable s) and is not a method I can change
methodToCall(T);
methodToCall(Class<T>);
methodToCall(T.class);
//do some more stuff
}
}
public class NonGenericClass extends GenericClass<DesiredClass> {
}
The Class object type is serializable so this works:
methodToCall(DesiredClass.class);
But I can't easily override the method because I'd just end up copying all the code since the class type is needed in the middle of the method.
Here's the best I've come up with so far:
public abstract class GenericClass<T> {
protected abstract void doStuff();
protected <T> void doStuff(Class<T> cls) {
methodToCall(cls);
}
}
public class NonGenericClass extends GenericClass<DesiredClass> {
@Override
protected void doStuff() {
doStuff(DesiredClass.class);
}
}
That works, but it feels like the generic class is wasting the knowledge that it has of what T is. Is there a syntax error in the 3 versions of calling methodToCall that I listed first? Is this something that just can't be done?
Hope this all makes sense.