这是我使用
Java Generics尝试做的简化示例.
void 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扩展B扩展C(扩展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扩展S>,然后转换为(S)输入但S总是等于T并且它导致堆栈溢出.