Why are interfaces not allowed as annotation members?

Deadly 提交于 2019-12-10 01:54:50

问题


Consider this code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Bar {
    Foo foo() default FooImpl.FooConstant;
}

Compiler error:

annotation value not of an allowable type

If I replace Foo with FooImpl the code is accepted.

What's the reason for this behavior?


回答1:


If I replace Foo with FooImpl the code is accepted.

I would be very surprised if this compiled, unless FooImpl is an enum.

Annotation members may only contain the following:

  • primitive type
  • String
  • Class literal
  • annotation
  • enum item
  • or 1-dimensional arrays of any of the above

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.

Source: JLS




回答2:


http://java.sun.com/docs/books/jls/third_edition/html/interfaces.html#9.7

The annotation member types must be one of: primitive, String, Class, an Enum, an array of any of the above

It is a compile-time error if the element type is not commensurate with the ElementValue.

Hope this helps!

Found the same in this documentation as well:

http://download.oracle.com/javase/1.5.0/docs/guide/language/annotations.html

"Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types." As mentioned "interface" is not allowed.



来源:https://stackoverflow.com/questions/7161190/why-are-interfaces-not-allowed-as-annotation-members

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!