问题描述
为什么我收到错误属性值必须是常量".null 不是常数吗???
Why am I getting an error "Attribute value must be constant". Isn't null constant???
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SomeInterface {
Class<? extends Foo> bar() default null;// this doesn't compile
}
推荐答案
我不知道为什么,但是JLS 很清楚:
I don't know why, but the JLS is very clear:
Discussion
Note that null is not a legal element value for any element type.
默认元素的定义是:
DefaultValue:
default ElementValue
不幸的是,我一直发现当您不符合语言规范时,新的语言功能(枚举和现在的注释)会产生非常无用的编译器错误消息.
Unfortunately I keep finding that the new language features (Enums and now Annotations) have very unhelpful compiler error messages when you don't meet the language spec.
通过谷歌搜索发现 遵循 JSR-308 中的,他们主张在这种情况下允许空值:
A little googleing found the following in the JSR-308, where they argue for allowing nulls in this situation:
我们注意到该提案可能存在一些反对意见.
提案没有使以前不可能实现的任何事情成为可能.
The proposal doesn't make anything possible that was not possible before.
程序员定义的特殊值提供了比 null 更好的文档,这可能意味着无"、未初始化"、null 本身等.
The programmer-defined special value provides better documentation than null, which might mean "none", "uninitialized", null itself, etc.
该提议更容易出错.忘记检查 null 比忘记检查显式值要容易得多.
The proposal is more error-prone. It's much easier to forget checking against null than to forget checking for an explicit value.
该提案可能会使标准习语更加冗长.目前只有注释的用户需要检查其特殊值.根据提案,许多处理注解的工具将不得不检查字段的值是否为空,以免抛出空指针异常.
The proposal may make the standard idiom more verbose. Currently only the users of an annotation need to check for its special values. With the proposal, many tools that process annotations will have to check whether a field's value is null lest they throw a null pointer exception.
我认为只有最后两点与为什么不首先做"有关.最后一点当然提出了一个好点 - 注释处理器永远不必担心他们会在注释值上获得空值.我倾向于认为,注释处理器和其他此类框架代码的工作更多地必须进行这种检查,以使开发人员的代码更清晰,而不是相反,但这肯定会使更改它的理由变得困难.
I think only the last two points are relevant to "why not do it in the first place." The last point certainly brings up a good point - an annotation processor never has to be concerned that they will get a null on an annotation value. I tend to see that as more the job of annotation processors and other such framework code to have to do that kind of check to make the developers code clearer rather than the other way around, but it would certainly make it hard to justify changing it.
这篇关于为注释字段设置默认空值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!