How to create custom Annotation in Java

You may or may already be familier with Java Annotations as they are alredy very common, specially if you are working with IDEs they mark the required code with annotations whenever required, but this is an Ideal article for you if you are looking to create a custom annotation, to the point and to the work.


This tutorial is a very sort one and to the point. In this tutorial you are going to see the example of how you can create your own annotation in Java.

Before we rush to the code part let us take a look at what are the annotations.

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.

Now this is the official definition of Annotation from the original Java SE docs. But in simpler terms you can sy the Annotations are the tags we add to a program which tells us,Compiler or JVM about the intention of that program.

You may already know many annotations like @Override or @SuppressWarning annotation, but this context doesn’t takes a dig on already described annotations but goes on with the syntax with witch you can define your own annotations and later on can use that in a program you are coding.

The declaration of the Annotation is similar to that of Interface but the keyword interface is preceded by ‘@’ symbol. and the annotation parameters are defined in a way you define the methods in Interface. For example take into account the annotation which can be used to mark the authorship of a class. However you can mark anything from the class to the data field or method with this annotation.

@Interface Author{
	String author();
   String date();
   float revisionNumber() default 1.0;
	String purpose();
}

In the above code we have created a custom annotation called Author which can be used to mark any piece of code for its authorship, like the way we present in following code example.

@Author(
	author="ExamsMyantra",
	date="2015-10-03",
	purpose="This class serves as a Demo for the example code for the use of custom annotation"
)
public class Demo{
	/*
		Class code goes here
	*/

	@Author(
		author="ExamsMyantra",
		date="2015-10-03",
		purpose="This method serves as a Demo for the example code for the use of custom annotation"
	)
	private void demoMethod(){
		/*
			demo method code goes here
		*/
	}
}

Simple, right ? Well this is how custom annotation can be created. Give it a try and don’t forget to point it out if we are doing something is wrong.