Java Custom Annotations: Create Your Own @interface
Java custom annotations are annotation types you declare yourself with the @interface keyword. They let you attach your own metadata, such as "this method needs admin access" or "this field must not be blank", and then read it with your own code at runtime.
Frameworks are built this way: JUnit's @Test, Spring's @GetMapping and Jakarta Validation's @NotBlank are all ordinary custom annotations plus code that reads them. In Java Built-in Annotations you met the meta-annotations @Retention and @Target. This lesson uses them to design annotation types from scratch and ends with a small working validation framework.
Java Custom Annotations Syntax
An annotation type looks like an interface with @ in front of the keyword. Its abstract methods are called elements.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME) // how long it is kept
@Target(ElementType.METHOD) // where it may be used
public @interface AnnotationName {
String elementName(); // required element
int otherElement() default 10; // optional element with a default
}
| Part | Purpose |
|---|---|
@interface | Declares an annotation type |
@Retention | SOURCE, CLASS (default) or RUNTIME. Use RUNTIME to read it with reflection |
@Target | The kinds of declarations it may be placed on |
Element name() | A value the user supplies, like @AnnotationName(elementName = "x") |
default | Makes an element optional |
Note: Element methods take no parameters and cannot declare
throws. An annotation type cannot extend another type; every annotation type implicitly extendsjava.lang.annotation.Annotation.
Creating a Marker Annotation
The simplest custom annotation has no elements. Its presence alone carries the meaning. Here @AdminOnly marks methods that require an admin user:
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
@Retention(RetentionPolicy.RUNTIME) // keep it until runtime
@Target(ElementType.METHOD) // only on methods
@interface AdminOnly { }
public class MarkerDemo {
public void viewCourses() { }
@AdminOnly
public void deleteCourse() { }
@AdminOnly
public void issueRefund() { }
public static void main(String[] args) {
Method[] methods = MarkerDemo.class.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName)); // stable order
for (Method method : methods) {
if (method.isAnnotationPresent(AdminOnly.class)) {
System.out.println(method.getName() + " requires ADMIN role");
}
}
}
}
Output:
deleteCourse requires ADMIN role
issueRefund requires ADMIN role
How it works:
@interface AdminOnly { }declares the annotation type. It is package-private here, so it can live in the same file; in a real project it would bepublicin its own file,AdminOnly.java.isAnnotationPresent(AdminOnly.class)returnstrueonly for the two annotated methods.viewCoursesandmainare skipped.getDeclaredMethods()returns methods in no guaranteed order, so the code sorts them by name before printing.
Why @Retention(RUNTIME) Matters
If you forget @Retention, the default is CLASS: the annotation is stored in the .class file but hidden from reflection. This is the most common reason a custom annotation "does nothing".
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@interface NoRetention { } // default: CLASS
@Retention(RetentionPolicy.RUNTIME)
@interface WithRuntime { }
@NoRetention
@WithRuntime
public class RetentionCheck {
public static void main(String[] args) {
System.out.println("NoRetention visible? " + RetentionCheck.class.isAnnotationPresent(NoRetention.class));
System.out.println("WithRuntime visible? " + RetentionCheck.class.isAnnotationPresent(WithRuntime.class));
}
}
Output:
NoRetention visible? false
WithRuntime visible? true
How it works:
- Both annotations are written on the class, and both compile without errors.
- Only
@WithRuntimereaches the running program.@NoRetentionwas kept in the bytecode for tools but is invisible toisAnnotationPresent.
| Retention | Choose it when |
|---|---|
SOURCE | Only the compiler or an annotation processor needs it (like @Override) |
CLASS | A bytecode tool reads .class files but the program never does |
RUNTIME | Your code or a framework reads it with reflection (most custom annotations) |
Adding Elements and Default Values
Elements turn a label into structured data. Each element has a type, and the allowed types are limited.
| Allowed element type | Example |
|---|---|
| Primitive types | int version() default 1; |
String | String author(); |
Class / Class<?> | Class<?> handler() default Object.class; |
| Enum types | Level priority() default Level.MEDIUM; |
| Other annotation types | Label label(); |
| One-dimensional arrays of the above | String[] tags() default {}; |
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
enum Level { LOW, MEDIUM, HIGH }
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface TaskInfo {
String author(); // required: no default
int version() default 1; // primitive with default
Level priority() default Level.MEDIUM; // enum
String[] tags() default {}; // array, empty by default
Class<?> handler() default Object.class; // class literal
}
@TaskInfo(author = "Priya", priority = Level.HIGH, tags = {"billing", "cron"})
class InvoiceJob { }
@TaskInfo(author = "Karthik")
class CleanupJob { }
public class ElementsDemo {
public static void main(String[] args) {
for (Class<?> job : new Class<?>[] {InvoiceJob.class, CleanupJob.class}) {
TaskInfo info = job.getAnnotation(TaskInfo.class);
System.out.printf("%-11s author=%-8s v%d priority=%-6s tags=%s handler=%s%n",
job.getSimpleName(), info.author(), info.version(), info.priority(),
String.join(",", info.tags()), info.handler().getSimpleName());
}
System.out.println(InvoiceJob.class.getAnnotation(TaskInfo.class));
}
}
Output:
InvoiceJob author=Priya v1 priority=HIGH tags=billing,cron handler=Object
CleanupJob author=Karthik v1 priority=MEDIUM tags= handler=Object
@TaskInfo(handler=java.lang.Object.class, priority=HIGH, version=1, tags={"billing", "cron"}, author="Priya")
How it works:
getAnnotation(TaskInfo.class)returns an object that implementsTaskInfo. Callinginfo.author()returns the value written in the source.- Elements you leave out return their defaults:
CleanupJobgetsversion 1,MEDIUM, an emptytagsarray andObject.class. - The annotation's
toString()shows every element, including defaults. The order of elements in that text is decided by the JVM and may differ from the source.
Required Elements and Invalid Types
An element without a default is required. Leaving it out is a compile error:
@TaskInfo(version = 2) // author is missing
class ReportJob { }
MissingElem.java:10: error: annotation @TaskInfo is missing a default value for the element 'author'
@TaskInfo(version = 2) // author is missing
^
1 error
Types outside the table, and null as a value, are rejected too:
import java.time.LocalDate;
@interface Release {
LocalDate date(); // not an allowed element type
String notes() default null; // null is never allowed
}
BadElem.java:5: error: element value must be a constant expression
String notes() default null; // null is never allowed
^
BadElem.java:4: error: invalid type for annotation interface element
LocalDate date(); // not an allowed element type
^
2 errors
Note: Because
nullis not allowed, use a sentinel default instead, such as""for strings,{}for arrays,-1for numbers orObject.classfor classes, and check for it in your processing code.
The value() Element Shortcut
If an element is named value, users may omit the name when it is the only element they set. Annotations can also target several kinds of declarations at once, such as fields and parameters.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@interface Label {
String value(); // named "value": allows @Label("...")
boolean required() default false;
}
public class ValueDemo {
@Label("Full name")
private String name;
@Label(value = "Mobile number", required = true)
private String phone;
public void register(@Label("Course code") String courseCode, int seats) { }
public static void main(String[] args) throws ReflectiveOperationException {
for (String fieldName : new String[] {"name", "phone"}) {
Field field = ValueDemo.class.getDeclaredField(fieldName);
Label label = field.getAnnotation(Label.class);
System.out.println("field " + field.getName() + " -> \"" + label.value() + "\" required=" + label.required());
}
Method register = ValueDemo.class.getMethod("register", String.class, int.class);
for (Parameter parameter : register.getParameters()) {
Label label = parameter.getAnnotation(Label.class);
System.out.println("parameter " + parameter.getType().getSimpleName() + " -> "
+ (label == null ? "(no label)" : label.value()));
}
}
}
Output:
field name -> "Full name" required=false
field phone -> "Mobile number" required=true
parameter String -> Course code
parameter int -> (no label)
How it works:
@Label("Full name")is short for@Label(value = "Full name"). Once you set a second element, as onphone, you must writevalue =explicitly.@Target({ElementType.FIELD, ElementType.PARAMETER})allows both fields and method parameters. Putting@Labelon a class would be a compile error.Field.getAnnotationandParameter.getAnnotationwork exactly likeClass.getAnnotation. Any reflective element (Class,Method,Field,Constructor,Parameter) can be asked for its annotations.
Reflection Methods for Reading Custom Annotations
All of these methods come from the AnnotatedElement interface, which Class, Method, Field, Constructor and Parameter implement.
| Method | Returns |
|---|---|
isAnnotationPresent(A.class) | true if annotation A is present |
getAnnotation(A.class) | The annotation, or null if absent |
getAnnotations() | All annotations, including @Inherited ones from superclasses |
getDeclaredAnnotations() | Only annotations written directly on this element |
getAnnotationsByType(A.class) | An array of A, unwrapping @Repeatable containers |
Note: Reflection itself is covered in detail in the Java Reflection API lesson. For annotations you only need the methods above.
Real-World Example: A Mini Validation Framework
Jakarta Validation (used by Spring Boot) checks form data with annotations like @NotBlank and @Size. This example builds a small version of it: three custom annotations, a class that uses them, and a validator that reads them at runtime.
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
// ---------- 1. The annotation types ----------
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface NotBlank {
String message() default "must not be blank";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Range {
int min() default 0;
int max() default Integer.MAX_VALUE;
String message() default "is out of range";
}
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Pattern {
String regex();
String message() default "has an invalid format";
}
// ---------- 2. A class that uses them ----------
class StudentRegistration {
@NotBlank(message = "Name is required")
private final String name;
@NotBlank
@Pattern(regex = "^[\\w.+-]+@[\\w-]+\\.[\\w.]+$", message = "Email must look like name@example.com")
private final String email;
@Range(min = 16, max = 60, message = "Age must be between 16 and 60")
private final int age;
@Pattern(regex = "^[6-9]\\d{9}$")
private final String mobile;
StudentRegistration(String name, String email, int age, String mobile) {
this.name = name;
this.email = email;
this.age = age;
this.mobile = mobile;
}
}
// ---------- 3. The processor that reads them ----------
class Validator {
static List<String> validate(Object target) throws IllegalAccessException {
List<String> errors = new ArrayList<>();
for (Field field : target.getClass().getDeclaredFields()) {
field.setAccessible(true); // read private fields
Object value = field.get(target);
String fieldName = field.getName();
NotBlank notBlank = field.getAnnotation(NotBlank.class);
if (notBlank != null && (value == null || value.toString().isBlank())) {
errors.add(fieldName + ": " + notBlank.message());
continue; // no point checking further
}
Range range = field.getAnnotation(Range.class);
if (range != null) {
int number = (Integer) value; // int field is boxed by field.get
if (number < range.min() || number > range.max()) {
errors.add(fieldName + ": " + range.message() + " (got " + number + ")");
}
}
Pattern pattern = field.getAnnotation(Pattern.class);
if (pattern != null && value != null && !value.toString().matches(pattern.regex())) {
errors.add(fieldName + ": " + pattern.message());
}
}
return errors;
}
}
public class Validation {
public static void main(String[] args) throws IllegalAccessException {
List<StudentRegistration> forms = List.of(
new StudentRegistration("Asha Kumar", "asha@gocourse.in", 21, "9876543210"),
new StudentRegistration(" ", "ravi.at.mail", 14, "12345"),
new StudentRegistration("Meena", "", 35, "8123456789"));
int formNumber = 1;
for (StudentRegistration form : forms) {
List<String> errors = Validator.validate(form);
System.out.println("Form " + formNumber++ + ": " + (errors.isEmpty() ? "VALID" : errors.size() + " error(s)"));
errors.forEach(error -> System.out.println(" - " + error));
}
}
}
javac Validation.java
java Validation
Output:
Form 1: VALID
Form 2: 4 error(s)
- name: Name is required
- email: Email must look like name@example.com
- age: Age must be between 16 and 60 (got 14)
- mobile: has an invalid format
Form 3: 1 error(s)
- email: must not be blank
How it works:
- Declaring the rules. Each annotation has
RUNTIMEretention andFIELDtarget.message()has a sensible default, so@NotBlankalone works, while@NotBlank(message = "Name is required")overrides it. - Using the rules.
StudentRegistrationcontains no validation code at all. The rules sit next to the fields they describe, so they are easy to read and change. - Reading private fields.
setAccessible(true)lets the validator readprivate finalfields. This works because the classes are in the same unnamed module; in a modular app, the package must be opened to the validator, as shown in module-info in Java. - Form 2.
" "is blank,ravi.at.mailhas no@,14is belowmin = 16, and12345is not a 10-digit number starting with 6 to 9. Themobilefield uses the default message,has an invalid format. - Form 3. The email is empty, so
@NotBlankfails, and thecontinueskips the@Patterncheck that would add a second, redundant error. - Boxing.
field.get(target)returnsObject, so theint agearrives as anIntegerand is cast back. - Field order.
getDeclaredFields()happens to return fields in source order on the standard JVM, but the specification does not promise any order. A production framework would sort the errors or collect them in a map.
This is exactly how real frameworks work: annotation types carry the rules as data, and a processor applies them with reflection. Adding a new rule, such as @Email or @MaxLength, means one new @interface and one new if block in the validator, with no change to the classes being validated.