2011-08-23 104 views
10

考虑以下代码:为什么不允许接口作为注释成员?

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

编译器错误:

annotation value not of an allowable type

如果我用FooImpl替换Foo,则接受代码。

这种行为的原因是什么?

回答

7

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

3

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

注释构件类型必须是以下之一:原始的,字符串,类,枚举的任何上述

阵列它是一个编译时间错误,如果元素类型是与ElementValue不相称。

希望这会有所帮助!

实测值相同的本文档中,以及:

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

“返回类型被限制为原语,字符串,类,枚举,注解和前述类型的数组”。如上所述,“接口”是不允许的。

+0

我完成了第一句话,第二个似乎是问题。我想知道为什么这是不允许的注释... – soc

+3

@soc *我履行了第一句话*不,你没有。 '类<?扩展Foo> fooType()'是有效的,'Foo foo()'不是。 –

+0

认为Foo Foo()是一种方法(只是为了简单起见)......我们能否提到接口作为方法的返回类型? :) – Nik

相关问题