Java:有界类型的getClass() [英] Java: getClass() of bounded type

查看:149
本文介绍了Java:有界类型的getClass()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在使用仿制药时,我发现了一些东西。在下面的示例中, doStuff1 编译,但 doStuff2 不会:

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

public <T extends Foo> void doStuff1(T value) {
    Class<? extends Foo> theClass = value.getClass();
}

public <T extends Foo> void doStuff2(T value) {
    Class<? extends T> theClass = value.getClass();
}

所以,我查了对象的文档。 getClass()并发现:


实际结果类型为Class<? extends | X |>其中| X |是调用getClass的表达式的静态类型的擦除。

这让我有点好奇。为什么 getClass()这样设计?如果适用的话,我可以理解将类型转换为它们的原始类,但我认为没有明显的理由说明为什么它们必须使它同时杀掉 T 。有没有一个特定的原因,它也可以摆脱它,或者它只是一般让我们摆脱一切因为它更容易;谁还需要它呢?

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?

推荐答案

如果 getClass()返回 Class<?扩展X> ,没有什么不好的事情可以发生;实际上它会帮助很多用例。

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

唯一的问题是,它在理论上是不正确的。如果对象是 ArrayList< String> ,则其不能 Class< ArrayList<字符串>> - 没有这样的类,只有类< ArrayList>

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

这实际上与擦除无关。如果有一天Java获得完整的具体类型, getClass()仍然应该返回 Class<? extends | X |> ;但是应该有一个新方法,比如 getType(),它可以返回更详细的类型<?扩展X> 。 (但是, getType 可能会与许多现有的类冲突,并且有自己的 getType 方法)

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)

对于时间,因为 Class<?扩展X> 在很多情况下可能很有用,我们可以设计自己的方法来做到这一点

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 <X> Class<? extends X> myGetClass(X x){ ... }

但是可以理解他们不会放这种hack in standard lib。

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

这篇关于Java:有界类型的getClass()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆