Java 7中通用类的变量访问的更改 [英] Changes in access of variables for generic classes in Java 7

查看:222
本文介绍了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.

public class Test<T extends Test> {

  private final int _myVar;

  public Test(int myVar) {
    _myVar = myVar;
  }

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

  private static class TestContainer<T extends Test> {
    private final T _test;
    private TestContainer(T test) {
      _test = test;
    }
    public T get(){
      return _test;
    }
  }
}

get(TestContainer< T> container)方法中编译,出现错误:

In Java 7, it fails to compile in the get(TestContainer<T> container) method, with the error:


错误:_myVar在测试中有私人访问

error: _myVar has private access in Test

我不明白为什么不再编译 - 。变量 t T 类型,必须扩展 Test 。它试图从类中测试 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...

    推荐答案


    §4.9 ...然后交叉类型具有与具有空体,直接超类Ck和在出现交叉类型的相同包中声明的直接超接口T1',...,Tn'的类类型(§8)相同的成员。

    §4.9 ... Then the intersection type has the same members as a class type (§8) with an empty body, direct superclass Ck and direct superinterfaces T1', ..., Tn', declared in the same package in which the intersection type appears.

    根据我对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


    ...在其中出现交叉路口类型的相同包。

    ... declared in the same package in which the intersection type appears.

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆