Java annotations cannot access protected static fields from top class

Is this code valid?

public abstract class A { protected static final String c = "my const"; } @myAnnotation(value=Ac) public class B extends A { } 

Eclipse with JDK 1.6.0.23 accepts this, but Maven 2.2.1 with JDK 1.6.0.23 shows me the following compilation error:

c has secure access to A

+4
source share
4 answers

I think I see what is happening here. An annotation instance is actually an interface with a unique static initializer. The only thing that adds annotation specs is syntactic sugar and a reference to a method, class, or field. So when you enter value=cA , which is almost like adding a static initiator to the annotation. Annotation is not a subclass of A, so access is denied. Secure access includes access to the package, so when you move A to the same package as B, the annotation is also in the same package as A. It gets access. Very good question, and I think the behavior should be the same for both compilers. I think that Eclipse will allow you to customize what it sees as an error so that you can accept that they use unwanted, more restrictive behavior.

+1
source

Thanks to a comment from @adranale, I found another answer in the "Java Language Specification" section on "Access Control" . I don’t think it should work that way, but the relevant text regarding the β€œprotected” reads

Let C be the class in which the protected member m is declared. Access is permitted only inside the body of subclass S of C.

The body of the class is all the code in braces. Class annotations are outside the curly braces, so they do not have access. Interestingly, this logic does not apply to annotations of methods, parameters, fields, or local variables that are inside the class body.

+3
source

The annotations you are trying to fill with "const" try to access the class from the outside, using protected ones that cannot work. Eclipse uses its own compiler, so you should try a clean rebuild in Eclipse to make sure it works. I guess it won't be.

+2
source

This code will only compile if both A and B belong to the same package.

+1
source

Source: https://habr.com/ru/post/1415123/


All Articles