Java注解无法从上层访问受保护的静态字段 [英] Java annotation cannot access protected static fields from upper class
问题描述
此代码有效吗?
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 接受这个,但 Maven
2.2.1 with JDK 1.6.0.23 显示以下编译错误:
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 在 A 中有受保护的访问
c has protected access in A
推荐答案
我想我明白这里发生了什么.注释的实例实际上是具有唯一静态初始值设定项的接口.注释规范在顶部添加的唯一内容是语法糖和指向方法、类或字段的链接.因此,当您键入 value=c.A
时,这几乎就像在注释中添加静态初始化程序一样.注释不是 A 的子类,因此拒绝访问.受保护的访问包括包访问,因此当您将 A 移动到与 B 相同的包中时,注释也与 A 位于同一个包中.它获得访问权限.很好的问题,我认为两个编译器的行为应该相同.我认为 Eclipse 将允许您自定义它视为错误的内容,以便您可以让他们同意使用不受欢迎的、更具限制性的行为.
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.
这篇关于Java注解无法从上层访问受保护的静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!