Casting a supertype in generics (getting a universal supertype of a general type)

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) { //do something with input treating it as class 'cls' if (cls != null) { recursiveMethod(cls.getSuperclass(), 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.

+4
source share
2 answers

Here is an iterative approach that could solve your problem:

 public static <T> void iterateOverSupertypes(T input) { Class<?> clazz = input.getClass(); while (clazz.getSuperclass() != null) { clazz = clazz.getSuperclass(); } } 
+3
source

When you create a new A and pass it in your code, your object will always remain A, no matter what you do.

Things like casting and generics are just ways to tell the compiler which object class you expect, but don't change the behavior of the object. Therefore, I don’t see what you are trying to achieve by “considering it as a type T”, but the only way I can achieve this that I see is to pass the type, as you did in your example, without generics.

PS: Always remember: Java generators are just some way for the compiler to ensure type safety, but they won't be in compiled code.

+2
source

Source: https://habr.com/ru/post/1499753/


All Articles