views:

405

answers:

2

Today I wanted to create my first annotation interface following this documentation and I got the compiler error "Invalid type for annotation member":

public @interface MyAnnotation {
    Object myParameter;
    ^^^^^^
}

Obviously Object cannot be used as type of an annotation member. Unfortunately I could not find any information on which types can be used in general.

This I found out using trial-and-error:

String --> Valid

int --> Valid

Integer --> Invalid (Surprisingly)

String[] --> Valid (Surprisingly)

Object --> Invalid

Perhaps someone can shed some light on which types are actually allowed and why.

+10  A: 

It's specified by section 9.7 of the JLS. The annotation member types must be one of:

  • primitive
  • String
  • Class
  • an Enum
  • an array of any of the above

It does seem restrictive, but no doubt there are reasons for it.

skaffman
How does one find those pages/documents? I swear I google everytime before asking on StackOverlow and on many Java question someone posts a link to the JSL which answers my question. Why do I not find those pages via Google?!
DR
+1 precise answer.
KLE
The JLS isn't very google-friendly. You just need to know that it's there.
skaffman
the same information is also available in the annotation guide on sun's site (did find that googling): http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html
wds
Yes, I found that page, too, but I've must have missed that sentence, hidden in all that prose text. I've looked for something more table or list-like.
DR
+7  A: 

I agree with Skaffman for the Types available.

Additional restriction : it has to be a compile-time constant.

For example, the following are forbidden:

    @MyAnnot("a" + myConstantStringMethod())
    @MyAnnot(1 + myConstantIntMethod())
KLE
+1 good point there
skaffman