0
0
JavaHow-ToBeginner · 4 min read

How to Create Custom Annotation in Java: Syntax and Example

To create a custom annotation in Java, use the @interface keyword followed by annotation elements. You can specify retention policy and target using @Retention and @Target annotations to control where and how long the annotation is available.
📐

Syntax

Here is the basic syntax to define a custom annotation in Java:

  • @interface: Declares the annotation type.
  • @Retention: Specifies how long the annotation is retained (e.g., runtime, source).
  • @Target: Specifies where the annotation can be applied (e.g., method, field).
  • Annotation elements look like methods and can have default values.
java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface MyAnnotation {
    String value() default "default";
    int number() default 0;
}
💻

Example

This example shows how to create a custom annotation and use it on a method. It also demonstrates how to read the annotation value using reflection at runtime.

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

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Info {
    String author();
    String date();
    int version() default 1;
}

public class CustomAnnotationExample {

    @Info(author = "Alice", date = "2024-06-01", version = 2)
    public void annotatedMethod() {
        System.out.println("This method is annotated.");
    }

    public static void main(String[] args) throws Exception {
        CustomAnnotationExample obj = new CustomAnnotationExample();
        obj.annotatedMethod();

        Method method = obj.getClass().getMethod("annotatedMethod");
        if (method.isAnnotationPresent(Info.class)) {
            Info info = method.getAnnotation(Info.class);
            System.out.println("Author: " + info.author());
            System.out.println("Date: " + info.date());
            System.out.println("Version: " + info.version());
        }
    }
}
Output
This method is annotated. Author: Alice Date: 2024-06-01 Version: 2
⚠️

Common Pitfalls

Common mistakes when creating custom annotations include:

  • Not specifying @Retention, which defaults to CLASS and makes the annotation unavailable at runtime.
  • Using incorrect @Target values or omitting it, which can cause the annotation to be used in unintended places.
  • Forgetting to use default values for elements if they are optional.
  • Trying to use annotations like regular classes (they are interfaces).
java
/* Wrong: Missing @Retention means annotation not available at runtime */
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Target(ElementType.FIELD)
public @interface WrongAnnotation {
    String name();
}

/* Right: Add @Retention(RetentionPolicy.RUNTIME) to access at runtime */
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.annotation.ElementType;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface RightAnnotation {
    String name();
}
📊

Quick Reference

Summary tips for creating custom annotations:

  • Use @interface to declare an annotation.
  • Always specify @Retention to control annotation availability.
  • Use @Target to restrict where the annotation can be applied.
  • Define elements as methods; use default values for optional elements.
  • Access annotations at runtime with reflection if retention is RUNTIME.

Key Takeaways

Create custom annotations using the @interface keyword with optional elements.
Specify @Retention(RetentionPolicy.RUNTIME) to access annotations during runtime.
Use @Target to limit where annotations can be applied for safer code.
Annotation elements behave like methods and can have default values.
Access annotations via reflection to read their values in your program.