java - 意外的泛型行为

标签 java generics

我发现了奇怪的泛型行为。用两个词—— 我真正想要的是以最通用的方式使用 ComplexObject1,而我真正想念的是为什么定义的泛型类型(...扩展 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.

另请参阅Effective Java 2nd Edition,第 23 条:不要在新代码中使用原始类型。

关于java - 意外的泛型行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2445516/

相关文章:

Java 泛型,返回泛型扩展

java - 将 mySQL MAX 值设置为 java 变量

c++ - std::enable_if 的第二个参数有什么用?

c# - 推断子类的 C# 泛型类型

JavaFX 中心图像不起作用

typescript - 键入一组泛型推断类型

typescript - 如何在 Typescript 中使用可变元组类型?

java - 不使用内置函数逐字反转字符串

java - 最终字段是否保证字段值在不同线程中可见?

java - Lucene针对经常变化的文档的索引策略