javaannotationsgenerated-code

Is it possible to have a Java annotation that doesn't apply to any class, method, field, etc. Just the annotation itself generating code


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.


Solution

  • 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.