This is a simplified example of what I'm trying to do using Java Generics .
void <T> recursiveMethod(T input) { //do something with input treating it as type T if (/*need to check if T has a supertype*/) { recursiveMethod((/*need to get supertype of T*/) input); // NOTE that I am trying to call recursiveMethod() with // the input object cast as immediate supertype of T. // I am not trying to call it with the class of its supertype. // Some of you seem to not understand this distinction. } }
If we have a long chain of types A extends B, C (extends Object) continues, the call recursiveMethod(new A()) should be done as follows:
recursiveMethod(A input) -> A has supertype B recursiveMethod(B input) -> B has supertype C recursiveMethod(C input) -> C has supertype Object recursiveMethod(Object input) -> Object has no supertype -> STOP
I can do this without Generics as follows:
void recursiveMethod(Object input) { recursiveMethod(input.getClass(), input); } } private void recursiveMethod(Class cls, Object input) {
Can I do the same with Generics? . I tried to declare as <S, T extends S> , then listing as (S)input , but S always equal to T , and this leads to a stack overflow.
source share