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

前端之家收集整理的这篇文章主要介绍了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.f2er.com/java/125032.html

猜你在找的Java相关文章