java - 为注释字段设置默认空值时出错

标签 java annotations default

为什么我收到错误“属性值必须是常量”。 null 不是常量???

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface SomeInterface {
    Class<? extends Foo> bar() default null;// this doesn't compile
}

最佳答案

我不知道为什么,但是 JLS很清楚:

 Discussion

 Note that null is not a legal element value for any element type. 

并且默认元素的定义是:

     DefaultValue:
         default ElementValue

不幸的是,当您不符合语言规范时,我不断发现新的语言功能(枚举和现在的注解)具有非常无用的编译器错误消息。

编辑:稍微用谷歌搜索发现 following在 JSR-308 中,他们主张在这种情况下允许空值:

We note some possible objections to the proposal.

The proposal doesn't make anything possible that was not possible before.

The programmer-defined special value provides better documentation than null, which might mean “none”, “uninitialized”, null itself, etc.

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.

我认为只有最后两点与“为什么不首先做”有关。最后一点当然提出了一个很好的观点——注释处理器永远不必担心它们会在注释值上得到空值。我倾向于认为注释处理器和其他此类框架代码的工作更多是必须进行这种检查以使开发人员的代码更清晰,而不是相反,但这肯定会很难证明更改它的合理性。

关于java - 为注释字段设置默认空值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1178104/

相关文章:

Hibernate - AnnotationConfiguration 已弃用

java - 在 eclipse 中为生成的 toString、hashCode 和 equals 添加注解

configuration - 跨平台配置、选项、设置、首选项、默认值

java - 递归遍历二叉搜索树并按列打印数据

java - 无法使用Keycloak验证应用程序用户的登录

java - 如何使用camelCase将Hibernate实体字段映射到snake_case(下划线)数据库标识符

css - 浏览器字体默认

java - 操纵内存占用

java - 问题 java gradle "Could not find org.jnetpcap:jnetpcap:1.4.1."

C#: new file() - 根保存位置在哪里?