简体   繁体   English

Java泛型类型擦除

[英]Java generics type erasure

I'd like to ask about java type erasure rules. 我想问一下Java类型擦除规则。

If we have classes: 如果我们有课程:

public class Shape{}
public class Circle extends Shape{}


public class Base<T extends Shape>{
    T x;
    public void setX(T t){}
}

public class MainClass(){
    public static void main(String... _arg){
         Base<? extends Shape> bs = new Base<Circle>(); 
         bs.setX(new Circle()); // <- compilation problem
    }
}

Can you please explain me why calling setX() method causes compilation problem? 您能解释一下为什么调用setX()方法会导致编译问题吗?

Because the compiler doesn't know that new Circle is valid. 因为编译器不知道new Circle是有效的。 Consider this code: 考虑以下代码:

Base<? extends Shape> bs = new Base<Square>();  // Really a Base<Square> 
bs.setX(new Circle());

(FYI, a very similar example is given in the Java tutorial on wildcards .) (仅供参考, Java教程中关于通配符的例子非常相似。)

You may now exclaim "But the compiler can see it's really a Base<Square> !". 您现在可能会惊叹“但是编译器可以看到它实际上是Base<Square> !”。 But not in general. 但不是一般。 Consider this: 考虑一下:

Base<? extends Shape> bs = someInterface.getBaseOfSomeKindOfShape();
bs.setX(new Circle());

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

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