This article discusses the way of creating annotations in Java. It also shows how to apply annotations to other declarations. Finally it discusses
how to obtain annotation information at runtime using Reflection.
Annotation is a new feature introduced by J2SE 5 that allows programmers to embed additional information called metadata into a Java source file.
Annotations do not alter the execution of a program but the information embedded using annotations can be used by various tools during development and deployment.
Using the code
Creating an annotation is similar to creating an interface. But the annotation declaration is preceded by an
@ symbol. The annotation declaration itself is annotated
@Retention annotation. The
@Retention annotation is used to specify the retention policy,
which can be
RetentionPolicy.SOURCE retains an annotation only in the source file and discards it during compilation.
RetentionPolicy.CLASS stores the annotation in the .class file but does not make it available during runtime.
RetentionPolicy.RUNTIME stores the annotation in the .class file and also makes it available during runtime.
String author(); String date(); }
An annotation cannot have the
extends clause. However, annotations implicitly extend the
Annotation interface. The body of an annotation consists
of method declarations without body. These methods work like fields.
In the above example, I have created two members, author and date to represent information about the creator, and date of writing of the class and method.
Once an annotation is created, it can be applied to classes, methods, fields, parameters, enums, and so on. While applying an annotation to a declaration,
you must provide values for its members as follows:
public class Test
public static void testMethod()
System.out.println("Welcome to Java");
System.out.println("This is an example of Annotations");
public static void main(String args)
Annotations can be queried at runtime using Reflection as follows:
public static void showAnnotations()
Test test=new Test(); try
Class c=test.getClass(); Method m=c.getMethod("testMethod"); MyAnnotation annotation1=
System.out.println("Author of the class: "+annotation1.author());
System.out.println("Date of Writing the class: "+annotation1.date());
System.out.println("Author of the method: "+annotation2.author());
System.out.println("Date of Writing the method: "+annotation2.date());
In the above code, I have queried annotations applied to the class
Test as well as the method
To obtain annotation information for the class, the following statement is used:
To obtain annotation information for the method, the following statement is used:
The annotation information is printed by using annotation objects.
Points of interest
The Java program is compiled on the command line as follows:
and executed as follows: