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.
@interfaceA custom annotation is declared using the @interface keyword. You can control its behavior using meta-annotations such as @Retention and @Target.
// 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;
}
// 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");
}
}
Modify the annotation parameters below to see how the Java Reflection Engine would "see" them at runtime.
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.
RetentionPolicy.RUNTIME when annotations are processed at runtime@Target options