Advance Java

Learn New things from Rixosys

Annotation Quick Introduction

Annotations in Java

Annotations behave like metadata and provide data about a program that is not part of the program itself. They are used to associate program elements with the meta tags so that the compiler can generate interdependent code to support the annotated elements. Developing annotations helps in faster development of program. Multi-value annotations are used to pass the values to multiple data members.

Use of Annotations:

  • Compiler can use Annotations to detect errors or suppress warnings.
  • Software tools can process annotation information to generate code, XML files, and can also apply them to variables, parameters, fields type declarations, methods and constructors.
  • There are some Annotations that are available to be examined at runtime.

There are 3 types of Annotation in Java:

        1.  Marker

        2.  Single-Value

        3.  Multi-value/Full-value


1. Marker

Marker annotations do not contain any elements (except name). For example:

public @interface Example{


It can be used as:

   public void anymethod() {


2. Single-value

Single value annotations can be represented with the data and value pair or can be represented just by using the value only.

For Example:

public @interface Example{

  String showSomething();


It can be used as:

   @Example ("Hi ! How r you")
   public void anymethod(){



3. Multi-value/Full-value:

Multi-value annotations are used to pass the values to multiple data members.

For Example:

public @interface Example{

String showSomething();
int num; 
String name;


It can be used as: 

@Example (showSomething = "Hi! How r you", num=5, name="zulfiqar" )
public void anymethod{

// code here


While defining the annotation programmer must follow these rules:

Declare the annotation using @ followed by the interface keyword followed by the annotation name.

In an annotation method declaration should not throw any exception and should not contain any parameter.

Jdk 5 (aka Tiger) contains 2 types of annotations:

             1. Simple annotations

             2. Meta annotations

There are three types of Simple annotations:

             1. Override

             2. Depricated

             3. Suppresswarnings

There are four types of Meta annotations:

        1. Target

         2. Retention

         3. Documented

         4. Inherited