gpt4 book ai didi

java - Java 7 中泛型类变量访问的变化

转载 作者:太空狗 更新时间:2023-10-29 22:41:17 25 4
gpt4 key购买 nike

这是一些使用 Java 6 编译但不在 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;
}
}
}

在 Java 7 中,编译失败 get(TestContainer<T> container)方法,错误:

error: _myVar has private access in Test

我不明白为什么这不再编译 - 在我看来它应该。变量 t类型为 T ,它必须扩展 Test .它正在尝试访问字段 _myVar Test 的一个实例来自类(class)内部Test .

的确,如果我改变方法 get(TestContainer<T> container)对于以下内容,它会编译(没有警告):

public int get(TestContainer<T> container){
Test t = container.get();
return t._myVar;
}
  • 为什么这不再编译?
  • 这是 Java 6 中的错误吗?如果是,为什么?
  • 这是 Java 7 中的错误吗?

我用 google 搜索了 Oracle bug 数据库,但没有找到关于这个的任何东西......

最佳答案

§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>创建以下交集:

package <the same as of Test>;

class I extends Test {}

因此,当您访问 T 类型的成员时您实际上访问了交集类型的成员 I .由于私有(private)成员永远不会被子类型继承,因此访问此类成员会因编译错误而失败。另一方面,由于交集是

,因此允许访问包私有(private)(默认)和 protected 成员

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

关于java - Java 7 中泛型类变量访问的变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10782876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com