Custom annotation example in Java

Introduction

This tutorial shows, what is an annotation and how to write a custom annotation. I have taken the below concepts from Oracle documentation from the link http://docs.oracle.com/javase/tutorial/java/annotations/basics.html.

Annotations, a form of metadata, provide data about a program that is not part of the program itself. Annotations have no direct effect on the operation of the code they annotate.

Annotation was introduced in Java 1.5 and now annotations are heavily used in different java frameworks like Spring, JSF, Hibernate, JPA etc.

The simplest form of annotation is @Annotation. The @ (at) indicates to the compiler that what follows is an annotation.

For example the @override annotation:

@Override
void myMethod() {
    //code
}

The annotation can include elements, which can be named or unnamed, and there are values for those elements:

@Author(
    name = "Soumitra Roy",
    createdDate = "05/20/2014"
)
class MyClass() {
     //code
}

or

@SuppressWarnings(value = "unchecked")
void myMethod() {
    //code
}

If there is just one element named value, then the name can be omitted, as in:

@SuppressWarnings("unchecked")
void myMethod() {
    //code
}

If the annotation has no elements, then the parentheses can be omitted, as shown in the previous @Override example.

It is also possible to use multiple annotations on the same declaration:

@Author(name = "Anin Roy")
@EBook
class MyClass {
     //code
}

Usage of Annotation

Annotations can be applied to declarations of classes, fields, methods and other program elements.

Define Annotation Type

Suppose you want to add some brief comments about the class as shown below:

public class HelloWorld {
    // Author Name: Soumitra Roy
    // Created Date: 06/11/2013
    // Last modified Date: 14/10/2013
    // Last modified By: Soumitra Roy
    // Reviewers: Ram, Sam, Gopal
    // code goes here
}

To add the above metadata with an annotation, you must first define the annotation type as shown below:

@interface Comments {
     String authorName();
     String createdDate();
     String lastModifiedDate() default "N/A";
     String lastModifiedBy() default "N/A";
     String[] reviewers();
}

Annotation type definition is an interface definition where the keyword interface is preceded by @(AT) sign. Annotation body contains the elements and they look like methods. Element can have default value.

Once you define the Annotation type then you can use the Annotation as shown below:

@Comments (
     authorName = "Soumitra Roy",
     createdDate = "06/11/2013",
     lastModifiedDate = "14/10/2013",
     lastModifiedBy = "Soumitra Roy",
     // Note array notation
     reviewers = {"Soum", "Gour", "Sum"}
)
public class HelloWorld {
     //code goes here
}

If you want to get the Annotation information to be appeared in Javadoc-generated documentation, you must annotate @Comments definition with the @Documented annotation.

@Documented
@interface Comments {
     //annotation elements
}

Meta Annotations

Annotations that apply to other annotation type are called meta annotations. There are several meta-annotation types defined in java.lang.annotation.

@Retention – specifies how the marked annotation is stored:

  • RetentionPolicy.SOURCE – The marked annotation is retained only in the source level and is ignored by the compiler.
  • RetentionPolicy.CLASS – The marked annotation is retained by the compiler at compile time, but is ignored by the Java Virtual Machine (JVM).
  • RetentionPolicy.RUNTIME – The marked annotation is retained by the JVM so it can be used by the runtime environment.

@Documented – indicates that whenever the specified annotation is used those elements should be documented using the Javadoc tool.

@Target – marks another annotation to restrict what kind of Java elements the annotation can be applied to. A target annotation specifies one of the following element types as its value:

  • ElementType.ANNOTATION_TYPE can be applied to an annotation type.
  • ElementType.CONSTRUCTOR can be applied to a constructor.
  • ElementType.FIELD can be applied to a field or property.
  • ElementType.LOCAL_VARIABLE can be applied to a local variable.
  • ElementType.METHOD can be applied to a method-level annotation.
  • ElementType.PACKAGE can be applied to a package declaration.
  • ElementType.PARAMETER can be applied to the parameters of a method.
  • ElementType.TYPE can be applied to any element of a class.

@Inherited – indicates that the annotation type can be inherited from the super class. (This is not true by default.) When the user queries the annotation type and the class has no annotation for this type, the class’ superclass is queried for the annotation type. This annotation applies only to class declarations.

@Repeatable – introduced in Java SE 8, indicates that the marked annotation can be applied more than once to the same declaration or type use.

The above meta annotation can be applied similar to the @Documented meta annotation as shown in the previous example. For example,

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
@interface Comments {
     //annotation elements
}

Below is a complete example:

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Comments {
	String authorName();
	String createdDate();
	String lastModifiedDate() default "N/A";
	String lastModifiedBy() default "N/A";
	String[] reviewers();
}

Apply the above annotation as follows:

@Comments(authorName = "Soumitra Roy", createdDate = "06/11/2013", lastModifiedDate = "14/10/2013", lastModifiedBy = "Soumitra Roy", reviewers = { "Soum",
"Gour", "Sum" })
public class HelloWorld {
}

The complete example can be given below:

import java.lang.annotation.Annotation;
import java.util.Arrays;
public class TestAnnotation {
	/**
	* @param args
	*/
	public static void main(String[] args) {
		Class<HelloWorld> obj = HelloWorld.class;
		
		if (obj.isAnnotationPresent(Comments.class)) {
			Annotation annotation = obj.getAnnotation(Comments.class);
			Comments comment = (Comments) annotation;
			System.out.println("Author Name : " + comment.authorName());
			System.out.println("Created date : " + comment.createdDate());
			System.out.println("Last Modified date : " + comment.lastModifiedDate());
			System.out.println("Last Modified By : " + comment.lastModifiedBy());
			System.out.println("Reviewers : " + Arrays.toString(comment.reviewers()));
		}
	}
}

That’s all about creating custom annotation in Java.

Source Code

Download

Leave a Reply

Your email address will not be published. Required fields are marked *