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?
From the Annotations Reference: Return types are restricted to primitives, String, Class, enums, annotations, and arrays of the preceding types. So, yes, the type can be an enum that implements an interface, but not the interface itself.
Annotation types are a form of interface, which will be covered in a later lesson. For the moment, you do not need to understand interfaces. The body of the previous annotation definition contains annotation type element declarations, which look a lot like methods. Note that they can define optional default values.
You can annotate with @Service an implementation and autowire the interface. Spring will check for any object implementing this interface.
Marker interfaces define a type that is implemented by instances of the marked class; marker annotations do not. The existence of this type allows you to catch errors at compile time that you couldn't catch until runtime if you used a marker annotation.
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:
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With