Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is a parameter's private field visible to a generic method in Java 6 but not in Java 7? [duplicate]

Possible Duplicate:
Type-parameterized field of a generic class becomes invisible after upgrading to Java 7

public class Test{

    private String _canYouSeeMe = "yes";

    <T extends Test> void genericMethod(T hey){
        String s = hey._canYouSeeMe;
    }

    void method(Test hey){
        String s = hey._canYouSeeMe;
    }   
}

When building against JDK 1.6 this compiles just fine but against 1.7 there is a compiler error in genericMethod(): The field Test._canYouSeeMe is not visible

The error can be resolved by making _canYouSeeMe protected rather than private, but I'm just wondering what has changed from 1.6 to 1.7

like image 912
meta-meta Avatar asked Aug 01 '12 14:08

meta-meta


People also ask

How does a generic method differ from a generic type?

From the point of view of reflection, the difference between a generic type and an ordinary type is that a generic type has associated with it a set of type parameters (if it is a generic type definition) or type arguments (if it is a constructed type). A generic method differs from an ordinary method in the same way.

What is wrong with Java generics?

Many people are unsatisfied with the restrictions caused by the way generics are implemented in Java. Specifically, they are unhappy that generic type parameters are not reified: they are not available at runtime. Generics are implemented using erasure, in which generic type parameters are simply removed at runtime.

What is generics in Java What are advantages of using generics?

In a nutshell, generics enable types (classes and interfaces) to be parameters when defining classes, interfaces and methods. Much like the more familiar formal parameters used in method declarations, type parameters provide a way for you to re-use the same code with different inputs.


1 Answers

Subclasses (T) of a class (Test) never have access to the superclass' private fields. This was likely a bug in the Java 6 compiler that was fixed in Java 7.

Remember: T extends Test means that T is a subclass of Test. It does not mean that T's class is Test.class, which is the necessary condition for having private field & method access.

like image 57
Matt Ball Avatar answered Oct 15 '22 10:10

Matt Ball