gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:51:19 28 4
gpt4 key购买 nike

为什么我收到错误“属性值必须是常量”。 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com