Saturday, May 3, 2014

Annotations in Java

Why, how, where and when for Annotations


Annotations are meta-meta-object which can be used to describe other meta-object. Meta-object are class, field and method. Asking an object for its meta-object (e.g. anObj.getClass() ) is calledintrospection. The introspection can go further and we can ask a meta-object what are its annotations (e.g. aClass.getAnnotations). Introspection and annotations belong to what is called reflexion andmeta-programming.
An annotation needs to be interpreted in one way or another to to be useful. Annotations can be interpreted at development-time by the IDE or the compiler or at run-time by a framework.
Annotation is a very powerful mechanism and can be used in a lot of different ways:
  • to describe constraints or usage of an element: e.g. @Deprecated, @Override, or @NotNull
  • to describe the "nature" of an element, e.g. @Entity, @TestCase, @WebService
  • to describe the behavior of an element: @Statefull, @Transaction
  • to describe how to process the element: @Column, @XmlElement
In all case, an annotation is used to describe the element, which is frequently referred as its semantics.
Prior to JDK5, the information that is now contained in the annotations needed to be stored somewhere else, and XML files were frequently used. But it is more convenient to use annotations because they will belong to the Java code itself, and are hence much easier to manipulate than XML.
Usage of annotations:
  • Documentation, e.g. XDoclet
  • Compilation
  • IDE
  • Testing framework, e.g. JUnit
  • IoC container e.g. as Spring
  • Serialization, e.g. XML
  • Aspect-oriented programming (AOP), e.g. Spring AOP
  • Application servers, e.g. EJB container, Web Service
  • Object-relational mapping (ORM), e.g. Hibernate, JPA
  • and many more...
...have a look for instance at project Lombok, which uses annotation to define how to generate equalsor hashCode methods.

No comments:

Post a Comment