How do you define a custom annotation in Java?

How to Define a Custom Annotation:

  • Creating a custom annotation in Java involves defining the annotation type using the @interface keyword.
  • You can specify various elements in the annotation, such as methods that act as attributes, which can have default values.
  • Here’s a step-by-step guide to defining a custom annotation:
    1. Define the Annotation: Use the @interface keyword to create the annotation.
    2. Add Retention Policy: Use @Retention to specify how long the annotation is retained (e.g., at runtime, compile-time).
    3. Specify Target: Use @Target to define where the annotation can be applied (e.g., methods, classes, fields).

Example:

Here’s a simple example of defining a custom annotation:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
// Define the custom annotation  

@Retention(RetentionPolicy.RUNTIME) // The annotation is available at runtime

@Target(ElementType.METHOD) // The annotation can only be applied to methods

public @interface CustomAnnotation {

String value() default "default"; // An optional element with a default value

int number() default 0; // Another optional element

}

  • In this example:
    • RetentionPolicy.RUNTIME: The annotation is retained at runtime, allowing it to be accessed via reflection.
    • ElementType.METHOD: This annotation can only be applied to methods.
    • Elements: value and number are elements of the annotation with default values.

How to Use the Custom Annotation:

You can use the custom annotation on methods like this:

public class Test {
    @CustomAnnotation(value = "Hello", number = 5)
    public void annotatedMethod() {
        System.out.println("This method is annotated with CustomAnnotation.");
    }
}


Things to Keep in Mind:

  • No Constructor: Annotations cannot have constructors.
  • Element Types: The elements of an annotation can be of primitive types, String, Class, enums, other annotations, or arrays of these types.
  • Retention Policies: Depending on the intended use, you can choose different retention policies (SOURCE, CLASS, or RUNTIME).