这是一个使用Java泛型的简化示例。
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
,导致出现了堆栈溢出。
input.getClass().getSuperClass()
? - user902383Class
对象传递到recursiveMethod
中,我想将input
对象强制转换为其超类型(并在泛型中实现 - 这才是真正的问题)。这是两个非常不同的事情。无论如何,我更喜欢 sp00m 的迭代方法,它运行得很好,而这种递归方法根本不起作用。所以,没有必要再进一步解释了。=)
- ADTC