How to Create Your Own Annotations in Java in 5 minutes ?

Have you ever wondered how annotations in Java are created and wanted to create custom annotations of your own ? In this tutorial we will look at how to create your own custom annotations and use them in your applications to make your development life cycle easier. But, before that let us understand what annotations are.

What are annotations ?

Annotations are basically a type of metadata which essentially provides informations related to the program, but are actually separate from the actual program. It provides extra or additional information, so it acts as an alternative to the Java Marker interfaces. Annotation can be used by the compilers to suppress warnings, generate code, detect specific errors.

Steps to create your annotation

We start by creating a custom annotation with the @interface keyword. In the below code, we create a CustomAnnotation. We use @Target with the value ElementType.METHOD. This denotes that the annotation will be only applicable for methods. Similarly, we could have also used ElementType.TYPE or ElementType.FIELD to denotes a class or a field. This totally depends on our use case.

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface CustomAnnotation {
    String value();
}

Next, we will try to use this annotation in our class method.

public class ClassForAnnotation {

    @CustomAnnotation(value = "First")
    public void firstMethod() {
        System.out.println("Executing firstMethod...");
    }

    @MyCustomAnnotation(value = "Second")
    public void secondMethod() {
        System.out.println("Executing secondMethod...");
    }
}

Now let us look at one example of calling these methods from one another class:

import java.lang.reflect.Method;

public class AnnotationProcessor {

    public static void main(String[] args) {
        try {
            ClassForAnnotation classFrAnnotation = new ClassForAnnotation();
            Method[] methods = ClassForAnnotation.class.getDeclaredMethods();

            for (Method method : methods) {
                if (method.isAnnotationPresent(CustomAnnotation.class)) {
                    Cust custAnnotation = method.getAnnotation(CustomAnnotation.class);
                    String customValue = custAnnotation.value();
                    String methodOutput = (String) method.invoke(classFrAnnotation);

                    System.out.println(methodOutput + " Annotation value: " + customValue);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Now for the above code when executed via the main method, it would output the below:

Output:

Executing firstMethod... Annotation value: First
Executing secondMethod... Annotation value: Second

Leave a Comment