微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

考虑这个代码
@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

原文地址:https://www.jb51.cc/java/125032.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐