gpt4 book ai didi

java - 泛型中的父类(super class)型转换(获取泛型类型的泛型父类(super class)型)

转载 作者:搜寻专家 更新时间:2023-11-01 02:27:25 25 4
gpt4 key购买 nike

这是我尝试使用 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并导致堆栈溢出

最佳答案

这里有一个可以解决您的问题的迭代方法:

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

关于java - 泛型中的父类(super class)型转换(获取泛型类型的泛型父类(super class)型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18528389/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com