java 有界类型,Java:有界类型的getClass()

I noticed something while I was derping around with generics. In the example below, doStuff1 compiles but doStuff2 doesn't:

public void doStuff1(T value) {

Class extends Foo> theClass = value.getClass();

}

public void doStuff2(T value) {

Class extends T> theClass = value.getClass();

}

So, I looked up the documentation for Object.getClass() and found this:

The actual result type is Class extends |X|> where |X| is the erasure of the static type of the expression on which getClass is called.

This made me a bit curious. Why is getClass() designed this way? I can understand converting types to their raw classes if applicable, but I see no obvious reason why they'd necessarily have to make it also kill off T. Is there a specific reason why it also gets rid of it, or is it just a general "let's just get rid of everything because it's easier; who would ever need it anyway" approach?

解决方案

If getClass() returns Class extends X>, nothing really bad can happen; actually it'll help a lot of use cases.

The only problem is, it is not theoretically correct. if an object is an ArrayList, its class cannot be Class> - there is no such class, there is only a Class.

This is actually not related to erasure. If one day Java gets full reified types, getClass() should still return Class extends |X|>; however there should be a new method, like getType() which can return a more detailed Type extends X>. (though, getType may conflict with a lot of existing classes with their own getType methods)

For the timing being, since Class extends X> might be useful in a lot of cases, we can design our own method that does that

static Class extends X> myGetClass(X x){ ... }

but it's understandable they wouldn't put this kind of hack in standard lib.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值