Java Custom Annotations: Create Your Own @interface

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 235 of 306

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
}
PartPurpose
@interfaceDeclares an annotation type
@RetentionSOURCE, CLASS (default) or RUNTIME. Use RUNTIME to read it with reflection
@TargetThe kinds of declarations it may be placed on
Element name()A value the user supplies, like @AnnotationName(elementName = "x")
defaultMakes an element optional

Note: Element methods take no parameters and cannot declare throws. An annotation type cannot extend another type; every annotation type implicitly extends java.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 be public in its own file, AdminOnly.java.
  • isAnnotationPresent(AdminOnly.class) returns true only for the two annotated methods. viewCourses and main are 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 @WithRuntime reaches the running program. @NoRetention was kept in the bytecode for tools but is invisible to isAnnotationPresent.
RetentionChoose it when
SOURCEOnly the compiler or an annotation processor needs it (like @Override)
CLASSA bytecode tool reads .class files but the program never does
RUNTIMEYour 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 typeExample
Primitive typesint version() default 1;
StringString author();
Class / Class<?>Class<?> handler() default Object.class;
Enum typesLevel priority() default Level.MEDIUM;
Other annotation typesLabel label();
One-dimensional arrays of the aboveString[] 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 implements TaskInfo. Calling info.author() returns the value written in the source.
  • Elements you leave out return their defaults: CleanupJob gets version 1, MEDIUM, an empty tags array and Object.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 null is not allowed, use a sentinel default instead, such as "" for strings, {} for arrays, -1 for numbers or Object.class for 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 on phone, you must write value = explicitly.
  • @Target({ElementType.FIELD, ElementType.PARAMETER}) allows both fields and method parameters. Putting @Label on a class would be a compile error.
  • Field.getAnnotation and Parameter.getAnnotation work exactly like Class.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.

MethodReturns
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:

  1. Declaring the rules. Each annotation has RUNTIME retention and FIELD target. message() has a sensible default, so @NotBlank alone works, while @NotBlank(message = "Name is required") overrides it.
  2. Using the rules. StudentRegistration contains no validation code at all. The rules sit next to the fields they describe, so they are easy to read and change.
  3. Reading private fields. setAccessible(true) lets the validator read private final fields. 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.
  4. Form 2. " " is blank, ravi.at.mail has no @, 14 is below min = 16, and 12345 is not a 10-digit number starting with 6 to 9. The mobile field uses the default message, has an invalid format.
  5. Form 3. The email is empty, so @NotBlank fails, and the continue skips the @Pattern check that would add a second, redundant error.
  6. Boxing. field.get(target) returns Object, so the int age arrives as an Integer and is cast back.
  7. 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Custom Annotations: Create Your Own @interface and get answers drawn from it.

Signed-in readers only.