← Back to Chapters

Java Custom Annotations

? Java Custom Annotations

? Quick Overview

Custom annotations in Java allow developers to define their own metadata that can be attached to classes, methods, fields, parameters, or other program elements. These annotations are widely used for configuration, documentation, validation, and framework-level processing.

? Key Concepts

  • Annotations are metadata, not executable code
  • Custom annotations are created using @interface
  • Annotations can have elements (methods without bodies)
  • Retention policy controls availability at runtime
  • Target defines where the annotation can be applied

? Syntax & Theory

A custom annotation is declared using the @interface keyword. You can control its behavior using meta-annotations such as @Retention and @Target.

? View Code Example
// Custom annotation definition
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();
int count() default 1;
}

? Code Example(s)

? View Code Example
// Using the custom annotation on a method
public class Demo {

@MyAnnotation(value = "Test Method", count = 3)
public void show() {
System.out.println("Hello from annotated method");
}
}

⚡ Interactive Reflection Simulator

Modify the annotation parameters below to see how the Java Reflection Engine would "see" them at runtime.

 
JVM Runtime / Reflection API
Method: show()
Annotation: @MyAnnotation
---------------------------
Extracting value()... "Test Method"
Extracting count()... 3

Result: Ready to process method with custom metadata.

? Live Output / Explanation

Explanation

The @MyAnnotation annotation is applied to the show() method. At runtime, reflection can be used to read the annotation values and perform custom logic such as validation, logging, or configuration-based execution.

✅ Tips & Best Practices

  • Use meaningful names for annotation elements
  • Prefer RetentionPolicy.RUNTIME when annotations are processed at runtime
  • Keep annotations lightweight and focused
  • Document custom annotations clearly for team usage

? Try It Yourself

  • Create an annotation for role-based access control
  • Write a program to read annotation values using reflection
  • Experiment with different @Target options