This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Java in General and the fly likes Annotation attributes with type parameters Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "Annotation attributes with type parameters" Watch "Annotation attributes with type parameters" New topic
Author

Annotation attributes with type parameters

Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

When you define a Java interface, it's possible to declare a method with type parameters, for example like this:

The same thing does not work in an annotation. This, for example, is illegal:

I can get what I'm after by using the raw type Enum:

What exactly is the reason why it is not possible to declare annotation attributes with type parameters?

(Also posted here, but not getting any useful answers there...).


Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
Jesper de Jong
Java Cowboy
Saloon Keeper

Joined: Aug 16, 2005
Posts: 14074
    
  16

Aha, found an acceptable answer. I can just do this:

(Note the Enum<?> instead of the raw type Enum).

Section 9.6 of the Java Language Specification says:
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.

And then it says this under "Discussion":
Note that this does not conflict with the prohibition on generic methods, as wildcards eliminate the need for an explicit type parameter.

In other words, it suggests using wildcards instead of type parameters. Probably allowing type parameters would have made annotations a lot more complicated, so they were just left out of annotations, with the idea that wildcards should be enough for what you'd need.
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Annotation attributes with type parameters
 
Similar Threads
Extending a enum with enum's type
generic enum and the values() method
Generics and enums
Self Bound or Recursive Generics
Abstract Method in enum