Java注释无法从上层类访问受保护的静态字段 [英] Java annotation cannot access protected static fields from upper class

查看:66
本文介绍了Java注释无法从上层类访问受保护的静态字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此代码有效吗?

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

@myAnnotation(value=A.c)
public class B extends A {

}

带有JDK 1.6.0.23的

Eclipse接受此,但是带有JDK 1.6.0.23的Maven 2.2.1向我显示以下编译错误:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆