How to create custom Annotations in java and use them?

Java Annotations provide information about the code and they have no direct effect on the code they annotate. In this tutorial, we will learn about Java annotations, how to write custom annotation, annotations usage and how to parse annotations.

Creating Custom Annotations in Java

Creating custom annotation is similar to writing an interface, except that it interface keyword is prefixed with @ symbol. We can declare methods in annotation.

package test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

public @interface Test {

	String name() default "";
	String descrition() default "";


Using Custom Annotations in Java

The at sign character (@) indicates to the compiler that what follows is an annotation. For Example,

package test;

public class MyTest {

	@Test(name="My first test",descrition="My first testcase description")
	public void test()
		System.out.println("My first test");
	@Test(name="My Second test",descrition="My Second testcase description")
	public void test1()
		System.out.println("My Second test");
	public void test3()
		System.out.println("My Third test");

Java Annotation Parsing

We parse java annotations from a class. Please note that Annotation Retention Policy should be RUNTIME otherwise it’s information will not be available at runtime and we wont be able to fetch any data from it.

package test;

import java.lang.reflect.Method;

public class TestAnnotationParser {
	   public void parse(Class<?> clazz) {
	      Method[] methods = clazz.getMethods();
	      int pass = 0;
	      int fail = 0;
	      for (Method method : methods) {
	         if (method.isAnnotationPresent(Test.class)) {
	            try {
	            	Test test = method.getAnnotation(Test.class);
	            	System.out.println("Executing testcase:");
	            } catch (Exception e) {
	      System.out.println("Execution Finished");
	      System.out.println("Passed Testcases: "+pass);
	      System.out.println("Failed Testcases: "+fail);
	      System.out.println("Total testcases: "+(pass+fail));

package test;

public class MainClass {

	public static void main(String[] args) {
		TestAnnotationParser parser = new TestAnnotationParser();


Run You will see the following output.

Executing testcase:
Name:My first test
Description:My first testcase description
My first test

Executing testcase:
Name:My Second test
Description:My Second testcase description
My Second test

Execution Finished
Passed Testcases: 2
Failed Testcases: 0
Total testcases: 2

Leave a Reply

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