Annotations in Java – an introduction

Annotations were introduced in Java 5. Annotation is also know as metadata. Metadata is a set of data that describes and gives information about other data. Annotations are only metadata and do not(and should not) contain any business logic.

For example:

void childMethod() { 
    //method implementation 

In this code, @Override is the annotation. When this annotation is used with the method, it means that method (childMethod()) in the this case overrides the method defined in the super class.

Earlier than Java 5 there were ad hoc annotation like transient and @deprecated. transient indicates that a field should be ignored by the serialization subsystem. @deprecated (which is a javadoc tag)indicates that the method should no longer be used.

Annotations are similar to javadoc tags. Actually they complement javadoc tags. We should use javadoc tag if the intention is to affect or product documentation, else we should use annotation.

Annotations do not directly affect program semantics, but they do affect the way programs are treated by tools and libraries, which can in turn affect the semantics of the running program. Annotations can be read from source files, class files, or reflectively at run time.

Need for annotations

Before Java 5, comments were the only available option for associating metadata with application elements. However, comments are ignored by the compiler and comments are not available at runtime. And even if available, to get information from the comments we have to parse properly.

Uses of annotation

  • Provide information for the compiler – Compiler can use annotation to detect errors and suppress warnings.
  • Compile time and runtime processing – Annotations affect the way programs are treated by tools and libraries. Tools and libraries can use the Annotations to generate code.
  • Runtime processing – Annotations can be available at runtime and can affect the semantics of the running program.
  • Declarative programming – Its declarative programming style where the code tells what it is meant for and other information to process to the compiler or runtime environment.
  • Helps removing boilerplate code – Annotations help in removing boilerplate code. Frameworks like Axis, Spring, Hibernate make heavy use of annotations.