加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么不允许接口作为注释成员?

发布时间:2020-12-14 16:33:27 所属栏目:Java 来源:网络整理
导读:考虑这个代码: @Retention(RetentionPolicy.RUNTIME)@Target(ElementType.METHOD)public @interface Bar { Foo foo() default FooImpl.FooConstant;} 编译器错误: annotation value not of an allowable type 如果我用FooImpl替换Foo,代码被接受. 这个行为
考虑这个代码:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
    Foo foo() default FooImpl.FooConstant;
}

编译器错误:

annotation value not of an allowable type

如果我用FooImpl替换Foo,代码被接受.

这个行为的原因是什么?

解决方法

If I replace Foo with FooImpl the code is accepted.

如果这个编译,我会非常惊讶,除非FooImpl是一个枚举.

注释成员只能包含以下内容:

>原始类型
>字符串
>类文字
>注释
>枚举项
>或1维阵列

It is a compile-time error if the return type of a method declared in
an annotation type is any type other than one of the following: one of
the primitive types,String,Class and any invocation of Class,an
enum type (§8.9),an annotation type,or an array (§10) of one of the
preceding types. It is also a compile-time error if any method
declared in an annotation type has a signature that is
override-equivalent to that of any public or protected method declared
in class Object or in the interface annotation.Annotation.

资料来源:JLS

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读