Custom Annotations

Design Considerations

  • When designing an annotation type, you must consider the cardinality of annotations of that type.
  • It is now possible to use an annotation zero times, once, or, if the annotation's type is marked as @Repeatable, more than once.
  • It is also possible to restrict where an annotation type can be used by using the @Target meta-annotation.
  • For example, you can create a repeatable annotation type that can only be used on methods and fields.
  • It is important to design your annotation type carefully to ensure that the programmer using the annotation finds it to be as flexible and powerful as possible.

Retrieving Annotations

  • There are several methods available in the Reflection API that can be used to retrieve annotations.
  • The behavior of the methods that return a single annotation, such as
  • AnnotatedElement.getAnnotationByType(Class), are unchanged in that they only return a single annotation if one annotation of the requested type is present.
  • If more than one annotation of the requested type is present, you can obtain them by first getting their container annotation. In this way, legacy code continues to work.
  • Other methods were introduced in Java SE 8 that scan through the container annotation to return multiple annotations at once, such as
  • AnnotatedElement.getAnnotations(Class).

Footer with Map