Java通用类型推断奇怪的行为? [英] Java Generic Type Inference Strange Behavior?

查看:42
本文介绍了Java通用类型推断奇怪的行为?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以向我解释这种行为吗?

Can someone explain this behaviour to me:

注意:T从未在SomeThingGeneric中使用

   public static class SomeThingGeneric<T> {
        public List<String> getSomeList() {
            return null;
        }
    }

final SomeThingGeneric<Object> someThingGenericObject = new SomeThingGeneric<Object>();
final SomeThingGeneric<?> someThingGenericWildcard    = new SomeThingGeneric<Object>();
final SomeThingGeneric someThingGenericRaw            = new SomeThingGeneric<Object>();

for (final String s : someThingGenericObject.getSomeList()) { }   // 1 - compiles
for (final String s : someThingGenericWildcard.getSomeList()) { } // 2 - compiles
for (final String s : someThingGenericRaw.getSomeList()) { }      // 3 - does not compile!

(1)和(2)编译,但(3)失败并显示以下消息:

(1) and (2) compiles but (3) fails with following message:

incompatible types
found   : java.lang.Object
required: java.lang.String

如果有人想要完整的代码,请此处是.我已经在Java 5和6中对此进行了验证.

If anyone wants the full code, here it is. I have verified this in both Java 5 and 6.

推荐答案

好吧,尽管投票否决,这是一个有趣的问题.我相信问题的答案就在 JLS :

Well, this is an interesting question despite the downvotes. I believe the answer to the question lies in this portion of the JLS:

构造函数的类型(第8.8节),实例方法(第8.4节,第9.4节)或未继承的原始类型C的非静态字段(§8.3)M它的超类或超接口是对应的原始类型删除对应于通用声明中的类型C.

The type of a constructor (§8.8), instance method (§8.4, §9.4), or non-static field (§8.3) M of a raw type C that is not inherited from its superclasses or superinterfaces is the raw type that corresponds to the erasure of its type in the generic declaration corresponding to C.

有效地,您的方法 public List< String>在通过原始类型访问它的情况下,getSomeList 获得 public List getSomeList 的有效签名.因此,结果列表的列表迭代器然后返回"对象而不是字符串.

Effectively, your method public List<String> getSomeList gets an effective signature of public List getSomeList, in the scenario where you accessing it via a raw type. And as such, the list iterator for the resulting list then 'returns' objects instead of strings.

这篇关于Java通用类型推断奇怪的行为?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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