这是我尝试使用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.
}
}
如果我们有一长串类型A extends B extends C (extends Object),调用recursiveMethod(new A())
应该执行如下:
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
我可以在没有泛型的情况下做到这一点,如下所示:
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);
}
}
我可以使用泛型做同样的事情吗?我尝试过声明为<S, T extends S>
,然后强制转换为(S)input
但S
总是等于T
,这会导致堆栈溢出。