Limiting annotation usage to specific code contexts

Usage of each annotation can be customized, such as allowing the annotation only under certain conditions. For example, the built-in annotation @Returns can appear only on methods, not on classes. To restrict usage in this way, use the native Java java.lang.annotation.Target annotation on the declaration of your annotation and pass a list of targets. The target defines where the annotation can be used.

Declare targets with a list of instances of the java.lang.annotation.ElementType enumeration:

  • METHOD – This annotation can be used on a method. Gosu properties are dynamic and similar to methods, so use this target for Gosu properties.
  • TYPE – This annotation can be used on a type, including classes
  • FIELD – This annotation can be used on a field or enumeration constant. Because Gosu properties are dynamic and similar to methods, instead use METHOD for Gosu properties.
  • CONSTRUCTOR – This annotation can be used on a constructor
  • PARAMETER – This annotation can be used on a function argument (a parameter)
  • ANNOTATION_TYPE – This annotation can be used on annotation type declarations

Unlike Java, Gosu does not support the value LOCAL_VARIABLE for annotations on local variable declarations.

If an annotation uses no @Target annotation, the Gosu default is to allow the annotation on all parts of a type.

You can use the compact Gosu syntax to define lists of items by surrounding the values with braces ({}). Additionally, you can omit ElementType. before the static values for the enumerations.

For example, the following annotation declaration defines valid usage to be types, including Gosu classes, and methods:

package example

uses java.lang.annotation.ElementType
uses java.lang.annotation.Target

@Target({ METHOD, TYPE })
annotation MyAnnotation {
  function purpose() : String
  function importance() : int = 0
}