How to Write a Custom Annotation in Java With Reflection
Define a custom Java annotation with retention, target and parameters, read it with reflection, build a validator and see where processors fit.

Annotations look like magic until you write one. @Transactional, @Test, @NotNull and @GetMapping are all ordinary Java types with a special declaration syntax, and the "magic" is a framework reading them with reflection at startup or at run time. Once you see that, custom annotations become a useful tool for your own cross cutting rules: marking fields for validation, marking methods for auditing, tagging classes for a registry. This post builds one end to end, an @Audited annotation, shows how to read it, adds a second one for field validation with parameters and ends with the compile time alternative. If reflection itself is new, Java reflection basics and when not to use it gives the background.
Declaring an annotation
An annotation type is declared with @interface. Its elements look like methods and may have defaults:
package dev.javahacks.audit;
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Audited {
String action();
boolean logArguments() default false;
Sensitivity sensitivity() default Sensitivity.NORMAL;
enum Sensitivity { NORMAL, HIGH }
}Three meta annotations configure it. @Retention says how long the annotation survives:
| Policy | Kept in source | Kept in .class | Visible to reflection at run time |
|---|---|---|---|
SOURCE | Yes | No | No; for compiler checks and processors, like @Override |
CLASS (the default) | Yes | Yes | No |
RUNTIME | Yes | Yes | Yes |
An annotation your code reads with reflection must be RUNTIME; leaving the default is the classic mistake, because getAnnotation then returns null without any error. @Target restricts placement, here methods only, so putting @Audited on a class is a compile error: annotation interface not applicable to this kind of declaration. @Documented includes the annotation in generated Javadoc.
The element types are restricted: primitives, String, Class, enums, other annotations and one dimensional arrays of those. You cannot have an element of type List<String> or Object, and no element may be null, which is why defaults exist.
Using it
public class AccountService {
@Audited(action = "ACCOUNT_CLOSE", logArguments = true, sensitivity = Audited.Sensitivity.HIGH)
public void close(long accountId, String reason) {
// ...
}
@Audited(action = "ACCOUNT_VIEW")
public String view(long accountId) {
return "account " + accountId;
}
public void internal() { } // not audited
}Elements without a default must be given; action is required, and omitting it is a compile error. When an annotation has a single element named value, you may write @Name("x") without the name, a convention the standard annotations rely on.
Reading it with reflection
Reflection gives you the annotation as an instance of your annotation interface, so the elements are method calls:
public class AuditScanner {
public static void main(String[] args) {
for (Method m : AccountService.class.getDeclaredMethods()) {
Audited a = m.getAnnotation(Audited.class);
if (a != null) {
System.out.printf("%s -> action=%s logArgs=%s sensitivity=%s%n",
m.getName(), a.action(), a.logArguments(), a.sensitivity());
}
}
}
}close -> action=ACCOUNT_CLOSE logArgs=true sensitivity=HIGH
view -> action=ACCOUNT_VIEW logArgs=false sensitivity=NORMALThe scanner found two methods and used the defaults for the unspecified elements. This is the whole mechanism: a framework scans for the annotation, reads the values and acts. To make @Audited actually do something at call time, you intercept the method. A Java dynamic proxy can do it for interfaces:
public interface Accounts {
@Audited(action = "ACCOUNT_VIEW")
String view(long accountId);
}
public static <T> T audited(Class<T> type, T target, Consumer<String> sink) {
return type.cast(Proxy.newProxyInstance(type.getClassLoader(), new Class<?>[]{type},
(proxy, method, args) -> {
Audited a = method.getAnnotation(Audited.class);
if (a != null) {
sink.accept(a.action() + (a.logArguments() ? " " + Arrays.toString(args) : ""));
}
return method.invoke(target, args);
}));
}Spring AOP works the same way at a larger scale, producing proxies and reading @Transactional, @Cacheable and your custom annotations; see writing a Spring AOP logging aspect for the production-grade version of this idea. Note that the annotation is on the interface method here because proxies see interface methods; annotations on a class method are not visible through the interface.
A validation annotation with parameters
Fields, parameters and types can be annotated too. A small validator shows a typical use, an annotation read per field:
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface Length {
int min() default 0;
int max() default Integer.MAX_VALUE;
}public final class Validator {
public static List<String> validate(Object target) throws IllegalAccessException {
List<String> errors = new ArrayList<>();
for (Field f : target.getClass().getDeclaredFields()) {
Length rule = f.getAnnotation(Length.class);
if (rule == null) continue;
f.setAccessible(true);
Object value = f.get(target);
int len = value == null ? 0 : value.toString().length();
if (len < rule.min() || len > rule.max()) {
errors.add(f.getName() + " length " + len + " is outside " + rule.min() + ".." + rule.max());
}
}
return errors;
}
}
class SignUp {
@Length(min = 3, max = 20) String username = "ab";
@Length(max = 50) String bio = "short";
}
System.out.println(Validator.validate(new SignUp()));[username length 2 is outside 3..20]This is a toy, and the real thing is Jakarta Bean Validation, covered in Jakarta Bean Validation explained, which adds groups, message interpolation and class level constraints. It uses exactly this structure: a @Constraint meta annotation links your annotation to a validator class, and the framework finds and applies it.
Repeatable and inherited annotations
Two features trip people up. By default you cannot put the same annotation twice on one element. Mark it @Repeatable with a container annotation to allow it:
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Roles.class)
public @interface Role { String value(); }
@Retention(RetentionPolicy.RUNTIME)
public @interface Roles { Role[] value(); }
@Role("admin") @Role("auditor")
class ReportController { }
Role[] roles = ReportController.class.getAnnotationsByType(Role.class); // both, via the containergetAnnotation(Role.class) returns null when the annotation is repeated, because the compiler wrapped the two into the container; use getAnnotationsByType. The other feature is @Inherited, which makes a class annotation visible on subclasses, but only for classes, not for interfaces or methods. Spring goes further with meta annotations: @RestController is itself annotated with @Controller, and Spring's AnnotationUtils and MergedAnnotations understand composition. You can build your own by stacking annotations, which the plain reflection API will not resolve for you.
Compile time: annotation processors
Reflection is a run time cost and fails late. An annotation processor runs inside javac, reads annotations with SOURCE or CLASS retention and can generate source files or report errors during compilation. Lombok, MapStruct, Dagger and Hibernate's metamodel generator work this way. A processor skeleton, which prints a compile error for a misuse:
@SupportedAnnotationTypes("dev.javahacks.audit.Audited")
@SupportedSourceVersion(SourceVersion.RELEASE_25)
public class AuditedProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
for (Element e : env.getElementsAnnotatedWith(Audited.class)) {
if (!e.getModifiers().contains(Modifier.PUBLIC)) {
processingEnv.getMessager().printMessage(
Diagnostic.Kind.ERROR, "@Audited methods must be public", e);
}
}
return false;
}
}The error then appears at compile time, on the offending line, in the IDE, which is far better than a run time surprise. The cost is more build setup: the processor lives in its own module and is registered on the compiler's processor path. Reach for a processor when you want generated code or compile time guarantees; use reflection for simple run time behaviour.
Design advice
Keep annotations declarative. They say *what* is true of a program element (@Audited(action = ...)), and the handler decides what to do about it. Avoid putting behaviour in the annotation, avoid giant annotations with a dozen elements and prefer an enum to a magic string where the values are a closed set. Name them as adjectives or nouns that read in front of a declaration. Document the retention and target decisions, since they are the contract between the annotation and its reader. And do not create an annotation when a method call would do: a @Retry(times = 3) is convenient, but a plain wrapper function is easier to debug and test.
Documenting an annotation as an API
An annotation is a public API of your codebase, and the people who use it never read the processor behind it. Put the contract in the annotation's Javadoc: what it means, where it may be placed, what the elements default to and what happens when it is missing. List the retention and target decisions so the next maintainer does not change them by accident, and add a test that fails if the annotation loses runtime retention, since the symptom of that mistake is a silent no-op. A short example in the Javadoc is worth more than a paragraph of description.
When this does not apply
For ordinary application logic, a method call is simpler and easier to follow than an annotation plus a scanner. If your goal is validation, use Jakarta Bean Validation instead of rolling your own. If your goal is code generation, an annotation processor or a build plugin is better than reflection. The references are the Java Tutorials on annotations and the [java.lang.annotation package documentation](https://docs.oracle.com/en/java/javase/25/docs/api/java.base/java/lang/annotation/package-summary.html).


