Java Tutorial

Operators

Flow Control

String

Number and Date

Built-in Classes

Array

Class and Object

Inheritance and Polymorphism

Exception Handling

Collections, Generics and Enumerations

Reflection

Input/Output Stream

Annotation

Java Annotation

Annotations in Java are a way to add metadata to your code that can be processed during compilation or at runtime. They provide a powerful mechanism for extending the functionality of your code without modifying it directly. In this tutorial, you will learn how to create and use custom annotations in Java.

  • Define a custom annotation

To define a custom annotation, use the @interface keyword followed by the annotation's name. Here, we create a simple @Author annotation that can be used to store the author's name and the creation date of a class or method:

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.TYPE, ElementType.METHOD})
public @interface Author {
    String name();
    String date();
}

The @Retention and @Target annotations are meta-annotations used to define the characteristics of your custom annotation:

  • @Retention specifies when the annotation should be available. In this case, we set it to RetentionPolicy.RUNTIME so the annotation will be available during the runtime of the program.
  • @Target defines where the annotation can be applied. Here, we allow the annotation to be applied to both types (classes, interfaces, etc.) and methods.
  • Apply the custom annotation

Now, let's create a class and a method with the @Author annotation:

@Author(name = "John Doe", date = "2023-05-04")
public class SampleClass {

    @Author(name = "Jane Smith", date = "2023-05-04")
    public void sampleMethod() {
        System.out.println("This is a sample method.");
    }
}
  • Process the custom annotation

Next, we'll create a class with a main method to process the custom annotations at runtime:

import java.lang.reflect.Method;

public class AnnotationProcessor {
    public static void main(String[] args) {
        // Get the SampleClass class object
        Class<?> sampleClass = SampleClass.class;

        // Check if the class is annotated with @Author
        if (sampleClass.isAnnotationPresent(Author.class)) {
            // Get the @Author annotation instance
            Author authorAnnotation = sampleClass.getAnnotation(Author.class);

            // Print the author's name and date
            System.out.println("Class author: " + authorAnnotation.name() + ", date: " + authorAnnotation.date());
        }

        // Iterate through the class's methods
        for (Method method : sampleClass.getDeclaredMethods()) {
            // Check if the method is annotated with @Author
            if (method.isAnnotationPresent(Author.class)) {
                // Get the @Author annotation instance
                Author authorAnnotation = method.getAnnotation(Author.class);

                // Print the author's name and date
                System.out.println("Method '" + method.getName() + "' author: " + authorAnnotation.name() + ", date: " + authorAnnotation.date());
            }
        }
    }
}
  • Run the program

Compile and run the AnnotationProcessor class, and you should see the following output:

Class author: John Doe, date: 2023-05-04
Method 'sampleMethod' author: Jane Smith, date: 2023-05-04

This tutorial demonstrates how to create and use custom annotations in Java. Annotations can be a powerful way to add metadata to your code and perform tasks such as generating code, validating input, or implementing aspect-oriented programming.

  1. Creating Custom Annotations in Java: You can create custom annotations by using the @interface keyword. Custom annotations can be used to add metadata to code or trigger specific behaviors.

    // Custom annotation definition
    public @interface MyAnnotation {
        String value() default "Default";
    }
    
    // Using the custom annotation
    @MyAnnotation("Custom Value")
    public class MyClass {
        // Class implementation
    }