1

Are there such things as Java annotations that aren't tied to any class, method, field, etc.?

Like just writing

@MyAnnotation(someParameter=value, ...)

by itself, and it generates code.

It seems like ExecutableType might define what kinds of "elements" an annotation can annotate, but I'm not sure. If that's true, then ExecutableType derives from TypeMirror, one of whose members are NoType. So maybe it's possible? But I cannot find an example of this.

Andrew Cheong
  • 29,362
  • 15
  • 90
  • 145
  • 1
    No, you cannot have an annotation by itself - annotations must be placed on types, methods, fields, local variables, packages or method parameters. It's [`java.lang.annotation.ElementType`](https://docs.oracle.com/javase/8/docs/api/java/lang/annotation/ElementType.html), used in the `@Target` meta-annotation, that determines on which types of elements a specific annotation can be used. See also [JLS 9.6.4.1](https://docs.oracle.com/javase/specs/jls/se8/html/jls-9.html#jls-9.6.4.1) – Jesper Jun 13 '19 at 07:56
  • Chances are an `enum` can provide the functionality you need... Have you looked into that? – ernest_k Jun 13 '19 at 07:59
  • The definition of "annotation" is that it is applied to something. The general english definition is something like "a note **added to** a text". If it wasn't "added to" something, then it would be a plain *note*, not an *annotation*. So, *by definition*, an annotation cannot stand by itself. – Andreas Jun 13 '19 at 08:12
  • @Jesper - Would you like to add it as an answer so I can accept? /@ernest_k - Hm, no, let me think about that, thanks! /@Andreas - Makes sense. – Andrew Cheong Jun 13 '19 at 14:21

1 Answers1

1

You cannot have a stand-alone annotation in Java.

Annotations can be applied to different things, for example: types, methods, fields, local variables, packages, method parameters and also on annotation definitions.

One annotation that is meant to be used on annotation definitions (therefore it's called a "meta-annotation") is @Target, which you use to indicate on what things the annotation you are defining is allowed to be used. You do this by specifying one or more element types as an argument to the @Target annotation - see the API docs of java.lang.annotation.ElementType.

The Java Language Specification paragraph 9.6.4.1 explains what annotations can be used on in more detail.

Jesper
  • 202,709
  • 46
  • 318
  • 350