本文介绍了Java 7中通用类的变量访问的更改的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是一些使用Java 6编译但不在Java 7中编译的代码的简单示例。

Here is a simple example of some code that compiles using Java 6, but does not compile in Java 7.

 c访问 Test 实例的字段 _myVar  / code>。

I don't understand why this no longer compiles - in my mind it should. The variable t is of type T, which must extend Test. It's trying to access the field _myVar of a instance of Test from within the class Test.

确实,如果我改变方法 get(TestContainer< T&到下面,它编译(没有警告):

Indeed, if I change the method get(TestContainer<T> container) to the following, it compiles (with no warnings):

public int get(TestContainer<T> container){
  Test t = container.get();
  return t._myVar;
}




  • 为什么不再编译?

  • 这是Java 6中的错误吗?如果是这样,为什么?

  • 这是Java 7中的错误吗?

  • 一个google并在Oracle错误数据库中搜索,但没有找到任何东西...

    I've had a google and searched in the Oracle bug database, but haven't found anything on this...

    推荐答案

    根据我对JLS部分的理解,你的情况下有一个类型变量< T extends Test> 创建以下交集:

    From my understanding of that JLS part, your case with a type variable <T extends Test> creates the following intersection:

    package <the same as of Test>;
    
    class I extends Test {}
    

    类型 T 您实际访问的交集类型 I 的成员。由于访问此类成员的子类从不继承私有成员,因此编译错误失败。另一方面,访问package-private(默认)和受保护的成员是允许的交集是

    Therefore when you access members of the type T you actually access members of the intersection type I. Since private members are never inherited by subtypes accessing such member fails with compile-error. On the other hand access to package-private (default) and protected members is allowed by the fact the intersection is

    这篇关于Java 7中通用类的变量访问的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 23:39