编程语言
首页 > 编程语言> > java-意外的泛型行为

java-意外的泛型行为

作者:互联网

我发现了奇怪的仿制药行为.用两个词-
我真正想要的是以最通用的方式使用ComplexObject1,而我真正想念的是为什么定义的泛型类型(… extended BuisnessObject)丢失了.
在我的博客中也可以讨论话题
http://pronicles.blogspot.com/2010/03/unexpected-generics-behaviour.html.

public class Test {

  public interface EntityObject {}

  public interface SomeInterface {}

  public class BasicEntity implements EntityObject {}

  public interface BuisnessObject<E extends EntityObject> {
    E getEntity();
  }

  public interface ComplexObject1<V extends SomeInterface> extends BuisnessObject<BasicEntity> {}

  public interface ComplexObject2 extends BuisnessObject<BasicEntity> {}

  public void test(){
    ComplexObject1 complexObject1 = null;
    ComplexObject2 complexObject2 = null;

    EntityObject entityObject1 = complexObject1.getEntity();
    //BasicEntity entityObject1 = complexObject1.getEntity(); wtf incompatible types!!!!
    BasicEntity basicEntity = complexObject2.getEntity();
  }
}

解决方法:

您的问题是您使用的是原始类型的ComplexObject1.易于修复:只需使用ComplexObject1<?>相反,您的代码可以正常编译.

对于这种行为,真的没有任何意外.

tutorial开始:

Type erasure exists so that new code may continue to interface with legacy code. Using a raw type for any other reason is considered bad programming practice and should be avoided whenever possible.

JLS 4.8 Raw Types(强调他们的):

The use of raw types is allowed only as a concession to compatibility of legacy code. The use of raw types in code written after the introduction of genericity into the Java programming language is strongly discouraged. It is possible that future versions of the Java programming language will disallow the use of raw types.

另请参见有效Java 2nd Edition,项目23:不要在新代码中使用原始类型.

标签:generics,java
来源: https://codeday.me/bug/20191210/2099936.html