Annotations of declarations

The Java platform lets you associate with each declaration zero or more annotations. They provide an extensible mechanism to associate properties with declarations. Kawa support for annotations is not complete (the most important functionality missing is being able to declare annotation types), but is fairly functional. Here is a simple example illustrating use of JAXB annotations: an XmlRootElement annotation on a class, and an XmlElement annotation on a field:

(define-alias XmlRootElement javax.xml.bind.annotation.XmlRootElement)
(define-alias XmlElement javax.xml.bind.annotation.XmlElement)
(define-simple-class Bib ( ) (@XmlRootElement name: "bib")
  (books (@XmlElement name: "book" type: Book) ::java.util.ArrayList))
(define-simple-class Book () ...)

This tutorial explains the JAXB example in depth.

Here is the syntax:

annotation ::= (@annotation-typename annotations-element-values)
annotations-element-values ::= annotation-element-value
  | annotation-element-pair ...
annotation-element-pair ::= keyword annotation-element-value
annotation-element-value ::= expression
annotation-typename ::= expression

An annotations-element-values consisting of just a single annotation-element-value is equivalent to an annotation-element-pair with a value: keyword.

Each keyword must correspond to the name of an element (a zero-argument method) in the annotation type. The corresponding annotation-element-value must be compatible with the element type (return type of the method) of the annotation type.

Allowed element types are of the following kinds:

Annotations are usually used in declarations, where they are required to be “constant-folded” to compile-time constant annotation values. This is so they can be written to class files. However, in other contexts an annotation can be used as an expression with general sub-expressions evaluated at run-time:

(define bk-name "book")
(define be (@XmlElement name: bk-name type: Book))
(be:name) ⇒ "book"

(This may have limited usefulness: There are some bugs, including lack of support for default values for annotation elements. These bugs can be fixed if someone reports a need for runtime construction of annotation values.)