Defining Custom Java Annotations: @interface, Elements, Retention and Target
Create your own Java annotations with @interface: declare elements and default values, restrict where they apply with @Target and ElementType, choose SOURCE, CLASS or RUNTIME retention, and understand the Annotation interface, proxies and dynamically computed defaults.
kvi5hnuCode Sprout team member8 min readOn this page
Article 105 showed how to use annotations. Frameworks are full of them, and sooner or later you'll want your own: a @Command for a CLI tool, a @Validate rule, an @Audited marker, or a @Describe that a processor turns into code. This article explains how to declare an annotation: its elements and their defaults, where it may be used (@Target), and how long it survives (@Retention).
Annotation interfaces
Every annotation is declared by an annotation interface, using the @interface syntax. Each method in the interface declares an element of the annotation. JUnit's @RepeatedTest, for example, is declared roughly like this:
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatedTest {
int value();
int failureThreshold() default Integer.MAX_VALUE;
String name() default "";
}
@interface creates a real Java interface. Tools that process annotations receive objects that implement it. When JUnit gets an object implementing RepeatedTest, it just calls failureThreshold() to learn the threshold for that particular test.
Element methods are restricted:
- no parameters, no
throwsclause, and not generic - the return type must be a primitive,
String,Class(optionallyClass<?>orClass<? extends T>), an enum, another annotation type, or a one-dimensional array of those - an annotation interface can also contain constants and nested types (the demo nests a
Statusenum inside@BugReport), but it can't extend other interfaces
All annotation interfaces implicitly extend java.lang.annotation.Annotation, which is a regular interface, not an annotation. You never extend annotation interfaces and never write classes that implement them. The compiler and the JVM create proxy objects when needed.
Default values
Add a default clause after the element method. It must be a constant of the right type, and never null:
public @interface BugReport {
String[] reportedBy() default {}; // an empty array
Reference ref() default @Reference(id = 0); // an annotation
Status status() default Status.UNCONFIRMED;
Class<?> testCase() default Void.class; // a "not set" sentinel
...
}
Elements without a default are required, so every use must supply them, as with value in @RepeatedTest. Reflection exposes the defaults through Method.getDefaultValue(), which returns null for required elements.
Meta-annotations: @Target and @Retention
@Target and @Retention are meta-annotations, annotations on annotation declarations. They say where the annotation may appear and how long it is kept.
@Target
The value of @Target is an array of ElementType constants listing the allowed positions. Use braces for several:
@Target({ElementType.FIELD, ElementType.RECORD_COMPONENT})
public @interface Describe { boolean withName() default true; }
The compiler enforces it. Putting @Describe on a method is a compile-time error.
| Element type | Annotation applies to |
|---|---|
ANNOTATION_TYPE | annotation interface declarations |
MODULE | modules |
PACKAGE | packages |
TYPE | classes (including enums and records) and interfaces (including annotation interfaces) |
METHOD | methods |
CONSTRUCTOR | constructors |
FIELD | fields (including enum constants) |
PARAMETER | method or constructor parameters |
RECORD_COMPONENT | record components (Java 16) |
LOCAL_VARIABLE | local variables |
TYPE_PARAMETER | type parameters (Java 8) |
TYPE_USE | uses of a type (Java 8) |
Without @Target, an annotation can go on any declaration, including type parameters and modules, but not on type uses such as List<@A String>. (Before Java 14, the JLS also excluded type parameters, so older articles may still say so.)
A record component annotation is passed along to the members generated from the component (field, accessor method, canonical-constructor parameter), but only to those whose kind is in the target list. Since @Describe targets FIELD, the width field of Tile(@Describe(withName = false) int width, int height) gets it, and the width() method doesn't. Add ElementType.METHOD if the accessor should get it too.
@Retention
@Retention decides how far the annotation travels:
RetentionPolicy.SOURCE: only for source-level tools such as the compiler and annotation processors. It isn't written to class files.@Overrideand@SuppressWarningsare examples.RetentionPolicy.CLASS: written to class files, where bytecode tools can find it, but the JVM doesn't make it available through reflection. This is the default when you omit@Retention, and a frequent surprise when a homemade annotation "doesn't work" at runtime.RetentionPolicy.RUNTIME: also available at runtime through reflection. Frameworks such as JUnit and JPA need this.

The rest of this part has an example for each policy. Runtime processing comes in article 108, source processing in article 109, and class-file processing in article 110. The other meta-annotations, @Documented, @Inherited and @Repeatable, are covered in article 107.
The Annotation interface
Every annotation object implements java.lang.annotation.Annotation:
annotationType()returns the annotation interface, such asRepeatedTest.class. Don't usegetClass(), which returns the generated proxy class (with a name likejdk.proxy2.$Proxy1), not the interface.equalsreturnstrueif the other object implements the same annotation interface and all element values are equal. Annotations behave like values.hashCodeis consistent withequalsand computed from the element names and values.toStringshows the annotation interface's name and the element names and values, roughly as the annotation would be written in source. The exact format has changed between Java versions, so don't parse it.
A complete example
The demo declares annotations with required and optional elements, every kind of default, a nested enum and a constant. It shows the three retention policies (only RUNTIME annotations are visible to reflection), targets including an annotation without @Target used on several declarations, and record-component propagation to a field but not a method. It also confirms that annotation interfaces are interfaces whose elements are methods, and that annotation objects are proxies with value-based equals and hashCode.
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
public class Solution {
// An annotation interface: each method is an element.
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface RepeatedTest {
int value(); // required: no default
int failureThreshold() default Integer.MAX_VALUE; // optional
String name() default "";
}
@Retention(RetentionPolicy.RUNTIME) public @interface Reference { int id(); }
@Retention(RetentionPolicy.RUNTIME)
public @interface BugReport {
enum Status { UNCONFIRMED, CONFIRMED, FIXED, NOTABUG }
boolean showStopper() default false;
String assignedTo() default "[none]";
Class<?> testCase() default Void.class;
Status status() default Status.UNCONFIRMED;
Reference ref() default @Reference(id = 0); // default for an annotation element
String[] reportedBy() default {}; // default: empty array
long[] lines() default {};
String NONE = "[none]"; // constants are allowed too
}
@Target({ElementType.FIELD, ElementType.RECORD_COMPONENT})
@Retention(RetentionPolicy.RUNTIME)
public @interface Describe { boolean withName() default true; }
// the three retention policies
@Retention(RetentionPolicy.SOURCE) @interface SourceOnly {}
@Retention(RetentionPolicy.CLASS) @interface InClassFile {} // the default
@interface NoRetentionGiven {} // CLASS as well
@Retention(RetentionPolicy.RUNTIME) @interface AtRuntime {}
// no @Target: allowed on any declaration, type parameters included (but not on type uses)
@Retention(RetentionPolicy.RUNTIME) @interface Anywhere {}
@Anywhere
static class Sample {
@Anywhere @Describe(withName = false) int size = 3;
@SourceOnly @InClassFile @NoRetentionGiven @AtRuntime
@RepeatedTest(5) void a() {}
@RepeatedTest(value = 5, failureThreshold = 2, name = "flaky") void b() {}
@BugReport(showStopper = true, status = BugReport.Status.CONFIRMED, ref = @Reference(id = 42),
reportedBy = {"Omar", "Fred"}, lines = {10, 20})
void c() {}
@BugReport void d() {}
@Anywhere Sample(@Anywhere int x) {}
Sample() {}
}
record Tile(@Describe(withName = false) int width, int height) {}
public static void main(String[] args) throws Exception {
System.out.println("-- retention policies --");
Method a = Sample.class.getDeclaredMethod("a");
var visible = new TreeSet<String>();
for (Annotation ann : a.getDeclaredAnnotations()) visible.add(ann.annotationType().getSimpleName());
System.out.println(" annotations on a() visible at runtime: " + visible);
System.out.println("-- elements and defaults --");
RepeatedTest ra = a.getAnnotation(RepeatedTest.class);
RepeatedTest rb = Sample.class.getDeclaredMethod("b").getAnnotation(RepeatedTest.class);
System.out.println(" a(): value=" + ra.value() + ", failureThreshold=" + ra.failureThreshold() + ", name=\"" + ra.name() + "\"");
System.out.println(" b(): value=" + rb.value() + ", failureThreshold=" + rb.failureThreshold() + ", name=\"" + rb.name() + "\"");
BugReport c = Sample.class.getDeclaredMethod("c").getAnnotation(BugReport.class);
BugReport d = Sample.class.getDeclaredMethod("d").getAnnotation(BugReport.class);
System.out.println(" c(): status=" + c.status() + ", ref=" + c.ref().id() + ", reportedBy=" + Arrays.toString(c.reportedBy())
+ ", lines=" + Arrays.toString(c.lines()) + ", testCase=" + c.testCase().getSimpleName());
System.out.println(" d() all defaults: showStopper=" + d.showStopper() + ", assignedTo=" + d.assignedTo()
+ ", status=" + d.status() + ", ref=" + d.ref().id() + ", reportedBy.length=" + d.reportedBy().length);
System.out.println(" constant in the annotation interface: BugReport.NONE = " + BugReport.NONE);
System.out.println(" element defaults via reflection: failureThreshold default = "
+ RepeatedTest.class.getDeclaredMethod("failureThreshold").getDefaultValue()
+ ", value default = " + RepeatedTest.class.getDeclaredMethod("value").getDefaultValue());
System.out.println("-- targets --");
System.out.println(" Describe targets: " + Arrays.toString(Describe.class.getAnnotation(Target.class).value()));
System.out.println(" Anywhere has @Target: " + Anywhere.class.isAnnotationPresent(Target.class)
+ "; used on class, field, constructor, parameter: "
+ Sample.class.isAnnotationPresent(Anywhere.class) + ", "
+ Sample.class.getDeclaredField("size").isAnnotationPresent(Anywhere.class) + ", "
+ Sample.class.getDeclaredConstructor(int.class).isAnnotationPresent(Anywhere.class) + ", "
+ Sample.class.getDeclaredConstructor(int.class).getParameters()[0].isAnnotationPresent(Anywhere.class));
System.out.println(" record component -> field: " + Tile.class.getDeclaredField("width").isAnnotationPresent(Describe.class)
+ ", -> accessor method (METHOD not a target): " + Tile.class.getDeclaredMethod("width").isAnnotationPresent(Describe.class));
System.out.println(" all element types: " + Arrays.toString(ElementType.values()));
System.out.println("-- annotation interfaces are interfaces --");
System.out.println(" isAnnotation: " + RepeatedTest.class.isAnnotation() + ", isInterface: " + RepeatedTest.class.isInterface()
+ ", extends Annotation: " + Annotation.class.isAssignableFrom(RepeatedTest.class));
System.out.println(" elements are methods: " + Arrays.stream(RepeatedTest.class.getDeclaredMethods()).map(Method::getName).sorted().toList());
System.out.println("-- annotation objects --");
System.out.println(" annotationType(): " + ra.annotationType().getSimpleName());
System.out.println(" getClass() is a generated proxy: " + Proxy.isProxyClass(ra.getClass())
+ ", same as the interface: " + (ra.getClass() == RepeatedTest.class));
RepeatedTest again = a.getAnnotation(RepeatedTest.class);
System.out.println(" equals same values: " + ra.equals(again) + ", hashCodes equal: " + (ra.hashCode() == again.hashCode())
+ ", equals different values: " + ra.equals(rb));
System.out.println(" toString mentions the values: " + (rb.toString().contains("failureThreshold=2") && rb.toString().contains("\"flaky\"")));
}
}
-- retention policies --
annotations on a() visible at runtime: [AtRuntime, RepeatedTest]
-- elements and defaults --
a(): value=5, failureThreshold=2147483647, name=""
b(): value=5, failureThreshold=2, name="flaky"
c(): status=CONFIRMED, ref=42, reportedBy=[Omar, Fred], lines=[10, 20], testCase=Void
d() all defaults: showStopper=false, assignedTo=[none], status=UNCONFIRMED, ref=0, reportedBy.length=0
constant in the annotation interface: BugReport.NONE = [none]
element defaults via reflection: failureThreshold default = 2147483647, value default = null
-- targets --
Describe targets: [FIELD, RECORD_COMPONENT]
Anywhere has @Target: false; used on class, field, constructor, parameter: true, true, true, true
record component -> field: true, -> accessor method (METHOD not a target): false
all element types: [TYPE, FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE, MODULE, RECORD_COMPONENT]
-- annotation interfaces are interfaces --
isAnnotation: true, isInterface: true, extends Annotation: true
elements are methods: [failureThreshold, name, value]
-- annotation objects --
annotationType(): RepeatedTest
getClass() is a generated proxy: true, same as the interface: false
equals same values: true, hashCodes equal: true, equals different values: false
toString mentions the values: true
Common questions
Why can't my framework find my annotation at runtime?
Most likely the annotation lacks @Retention(RetentionPolicy.RUNTIME). The default is CLASS, which keeps the annotation in the class file but hides it from reflection.
Why can't an annotation element default to null?
The class file format has no way to store null as an annotation value. Use a sentinel instead, such as an empty string, Void.class or a special enum constant meaning "not set".
Can one annotation interface extend another?
No. Annotation interfaces implicitly extend java.lang.annotation.Annotation and can't extend anything else. To combine annotations, frameworks such as Spring use "meta-annotations": an annotation annotated with other annotations, which the framework then looks for.
What happens to a record component annotation?
The compiler copies it to the generated field, accessor method and canonical-constructor parameter, but only to those kinds allowed by the annotation's @Target. With ElementType.RECORD_COMPONENT in the target, it is also visible through RecordComponent.getAnnotation.
How do I compare two annotation objects?
Use equals: two annotations are equal if they have the same annotation type and equal element values. Use annotationType() to find the type, not getClass(), which returns a proxy class.
API reference
java.lang.annotation.Annotation
| Method | Description |
|---|---|
Class<? extends Annotation> annotationType() | the annotation interface of this annotation object (not the proxy class) |
boolean equals(Object other) | true if other implements the same annotation interface with equal element values |
int hashCode() | hash code compatible with equals, from element names and values |
String toString() | the annotation interface name with element names and values |
Related reflection methods
| Method | Description |
|---|---|
boolean Class.isAnnotation() | true if the class object is an annotation interface |
Object Method.getDefaultValue() | default value of an annotation element, or null if none |
ElementType[] Target.value(), RetentionPolicy Retention.value() | read the meta-annotations of an annotation interface |
Summary
- Declare an annotation with
@interface. Each parameterless, non-generic method withoutthrowsis an element, of a primitive,String,Class, enum, annotation or a one-dimensional array of those. defaultclauses make elements optional. Defaults must be non-null constants and are looked up dynamically, so changing them affects already-compiled uses.@Targetlists the allowedElementTypes. Without it, the annotation fits any declaration but no type uses. Record-component annotations propagate only to matching targets.@RetentionselectsSOURCE,CLASS(the default) orRUNTIME. OnlyRUNTIMEannotations are visible through reflection.- Annotation objects are JVM-generated proxies. Use
annotationType(), notgetClass(), and rely on value-basedequals/hashCode.
Practice Questions
Your custom annotation is on a class, but clazz.getAnnotation(MyAnno.class) returns null. What is the most likely cause?
The annotation has no @Retention(RetentionPolicy.RUNTIME). Without it, the retention defaults to CLASS, so the annotation is in the class file but the JVM doesn't expose it through reflection.
Which of these element declarations are legal? int[] lines(); List<String> tags(); String name() default null; Class<?> type(); int[][] grid();
int[] lines() and Class<?> type() are legal. List<String> isn't an allowed element type, null can never be a default, and arrays of arrays aren't allowed.
An annotation with @Target(ElementType.FIELD) is placed on a record component. Which generated members carry it?
Only the private field generated for the component. The accessor method and the canonical-constructor parameter don't get it, because METHOD and PARAMETER aren't among its targets.
Why does annotation.getClass() not return the annotation interface?
Annotation objects are instances of proxy classes that the JVM generates to implement the annotation interface. getClass() returns that proxy class, while annotationType() returns the annotation interface itself.
What happens to already compiled classes if you change an element's default value and recompile just the annotation interface?
They see the new default. Defaults aren't stored with the annotated element. They're read from the annotation interface when requested, so every use that relied on the default changes behavior.
Previous: Java Annotations Explained: Syntax, Uses and Where You Can Annotate
Next: Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
Related reading
- Java Annotations Explained: Syntax, Uses and Where You Can Annotate
- Java Processes and ProcessBuilder: Running and Managing External Programs
- Java Long-Running Tasks in User Interfaces: Swing Worker Threads and Callbacks
- Java CompletableFuture: Asynchronous Programming with Callbacks and Composition
- Java ConcurrentHashMap, CopyOnWriteArrayList and Parallel Array Algorithms

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.