java 泛型 获取类型_java – 泛型中的超类型转换(获取泛型类型的泛型超类型)

这是我使用

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并且它导致堆栈溢出.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值