Java annotation cannot access protected static fields from upper class

寵の児 提交于 2019-12-01 21:27:53

问题


Is this code valid?

public abstract class A {
   protected static final String c = "my const";
}

@myAnnotation(value=A.c)
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 compile error:

c has protected access in A


回答1:


I think I see what is happening here. An instance of an annotations is effectively an interface with a unique static initializer. The only things the annotation spec adds on top are syntactic sugar and a link to the method, class or field. So when you type value=c.A that is almost like adding a static initilizer to the annotation. The annotation is not a subclass of A, so access is denied. Protected access includes package access, so when you move A into 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 Eclipse will let you customize what it treats as an error so you might be able to make them agree to both use the undesirable, more restrictive behavior.




回答2:


Thanks to the comment from @adranale I found a different answer in the Java Language Specification section on Access Control. I don't think it should work this way, but the relevant text regarding "protected" reads

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

The body of a class is all the code in curly brackets. Class anotations are outside the curly brackets, so they don't have access. Interestingly, this logic would not apply to method, parameter, field or local variable annotations which are inside the class body.




回答3:


The Annotation you are trying to fill with the "const" tries to access the class from outside by using protected that can't work. Eclipse uses it's own compiler so you should try to make clean rebuild in Eclipse to see if it's working. I assume it will not.




回答4:


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



来源:https://stackoverflow.com/questions/10814176/java-annotation-cannot-access-protected-static-fields-from-upper-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!