Defining your own annotations

You can define annotations to add entirely new metadata annotations, apply them to programming declarations, and optionally retrieve information at run time. You can also get information at run time about objects annotated with built-in annotations. For example, you could mark a Gosu class with metadata and retrieve it at run time.

You can define new annotation types that can be used in other Gosu code. Annotations are defined in .gs files like Gosu classes, but they use a different syntax for the declaration. Your annotation can take arguments, which can set metadata that can be queried by IDEs or dynamically at run time.

The declaration syntax:

  • Use the annotation keyword instead of using the class keyword.
  • Define each annotation argument as if it were a class method, ensuring you declare the return type
  • Append an equal sign and then the default value to specify a default value to an annotation argument.

For example, the following code defines an annotation with one String argument and one integer primitive, with a default value for the integer:

package example

annotation MyAnnotation {
  function purpose() : String
  function importance() : int = 0
}

You can now use this annotation on a new class:

package example

@MyAnnotation(:purpose="do the right thing", :importance=44)
class MyClass {
}

By default, this annotation can be used on any method, type, property, or constructor, and as many times as necessary.

Customizing annotation context and behavior

Gosu supports special annotations on an annotation declaration to customize its behavior. Annotations on an annotation declaration are called meta-annotations.

Setting inheritance of an annotation

Gosu supports the native Java meta-annotation @Inherited. It takes no arguments. Use it to indicate that this annotation is inherited by subtypes.

Setting documented status of an annotation

Gosu supports the native Java meta-annotation @Documented. It takes no arguments. This annotation indicates that an annotation is to be documented by automatic documentation tools.

See also