Changes in access of variables for generic classes in Java 7

后端 未结 3 940
借酒劲吻你
借酒劲吻你 2021-01-01 18:03

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

public class Test {

  private final         


        
相关标签:
3条回答
  • 2021-01-01 18:54

    See @pingw33n's comment for the answer, but the way to fix this is to remove the generic parameters on the nested class. Unless you have a use case where the inner and outer T's can be different, they are redundant. All they are doing is causing this grief.

    0 讨论(0)
  • 2021-01-01 19:05

    §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.

    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 {}
    

    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.

    0 讨论(0)
  • 2021-01-01 19:06

    A workaround for this is to cast the generic instance to the concrete supertype that declares the private field, e.g.

    public int get(TestContainer<T> container){
      T t = container.get();
      return ((Test) t)._myVar;
    }
    
    0 讨论(0)
提交回复
热议问题