Java - Annotation Java Annotations

Introduction

What Are Annotations?

Java annotation adds comment or explanation to Java code.

Syntax

Declaring an annotation type is similar to declaring an interface type.

An annotation type declaration is a special kind of interface type declaration.

You use the interface keyword preceded by the @ sign to declare an annotation type.

The following is the general syntax for declaring an annotation type:

<modifiers> @ interface <annotation-type-name> { 
 // Annotation body
} 
  

<modifiers> is the same as for an interface declaration.

You can declare an annotation type as public or package level.

@ sign and interface keyword may be separated by whitespaces or they can be placed together.

An annotation type name should be a valid Java identifier.

Example

The following code creates an annotation for the version information.

@interface Version { 
   int major(); 
   int minor(); 
} 

To create an instance of an annotation type and use it to annotate a program element, use the following syntax:

@annotationType(name1=value1, name2=value2, names3=values3...) 

name=value pairs do not have to appear in the same order as they are declared in the annotation type.

The following is an instance of your Version annotation type:

@Version(major=1, minor=0) 

You can rewrite the above annotation as @Version(minor=0, major=1).

You can use the annotation type's fully qualified name as

@com.book2s.annotation.Version(major=0, minor=1) 

You can use your Version annotation to document additions to the Main class in different releases.

@Version(major=1, minor=0) 
public class Main { 

} 

Both of the following declarations are technically the same:

@Version(major=1, minor=0) public class Main { 
} 
public @Version(major=1, minor=0) class Main { 
} 

Demo

@interface Version {
  int major();//  w  w w .  jav  a  2  s.com

  int minor();
}

// Annotation for class Main
@Version(major = 1, minor = 0)
public class Main {
  // Annotation for instance variable xyz
  @Version(major = 1, minor = 1)
  private int xyz = 110;

  // Annotation for constructor Main()
  @Version(major = 1, minor = 0)
  public Main() {
  }

  // Annotation for constructor Main(int xyz)
  @Version(major = 1, minor = 1)
  public Main(int xyz) {
    this.xyz = xyz;
  }

  // Annotation for the printData() method
  @Version(major = 1, minor = 0)
  public void printData() {
  }

  // Annotation for the setXyz() method
  @Version(major = 1, minor = 1)
  public void setXyz(int xyz) {
    // Annotation for local variable newValue
    @Version(major = 1, minor = 2)
    int newValue = xyz;

    this.xyz = xyz;
  }
}