简体   繁体   English

Java通用成员类型在子类中删除了?

[英]Java Generic member type erased in subclass?

I have a class with below member: 我有一个以下成员的课程:

public  class BaseContainer {
    protected LinkedHashMap<Enum, MyClass> places;
}

And a subclass where I use the protected member : 还有一个我使用受保护成员的子类:

public class NullContainer extends BaseContainer {
    public MyClass getSelectedPlace() {
        return places.values().iterator().next(); 
    }
}

And I get (In netbeans): 我得到(在netbeans中):
error: incompatible types 错误:类型不兼容
required : MyClass 必需的:MyClass
found : Object 找到:对象

Why do I need to cast now? 为什么现在需要投射? What happened with the type info? 类型信息发生了什么? Was it erased just because of inheritance? 只是因为继承而将其抹掉了吗? What am I doing wrong. 我究竟做错了什么。

Seems to be a bug in my java compiler then. 似乎是我的Java编译器中的错误。 Thanks all for the help. 谢谢大家的帮助。

So finally I think I found the answer to be a bug in jdk1.7.0_51 (which I am using). 所以最后我认为我发现答案是jdk1.7.0_51(我正在使用)中的错误。 https://bugs.openjdk.java.net/browse/JDK-8061736 However there are oppinions that this is not a bug (see the end of bugreport): https://bugs.openjdk.java.net/browse/JDK-8061736但是,有观点认为这不是错误(请参见bugreport的结尾):

The superclasses (respectively, superinterfaces) of a raw type are the erasures of the superclasses (superinterfaces) of any of its parameterized invocations. 原始类型的超类(分别是超接口)是其任何参数化调用的超类(超接口)的擦除。 So as GenList is a raw type the return type of method getAValue is not A or String but Object. 因此,由于GenList是原始类型,方法getAValue的返回类型不是A或String而是Object。 Which corresponds with javac's output. 与javac的输出相对应。

(I really think this is rather a bug, because all taht this achieves is that now I am forced to cast every occurence of this member field in all subclasses, which just doesn't make any sense...) (我真的认为这是一个错误,因为这样做的全部目的是现在我被迫在所有子类中强制转换该成员字段的所有出现,但这毫无意义...)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM