Java Annotation
Also known as:
Annotation
Custom Annotation
@interface
Java Annotations
Definition
A Java annotation is metadata attached to source code with an @Name tag. You declare a custom annotation with @interface, then control where it may appear with @Target and how long it is kept with @Retention. Annotations do not run by themselves. A compiler, an annotation processor, or runtime reflection has to read them and act. That is how JUnit finds @Test methods and how Spring honors @Autowired.
Popular reads
View All
Payment System Design: Ledger, Idempotency, and Settlement
Jul 18, 2026
The Complete HTMX Guide: From Zero to Production
Dec 22, 2025
How Google manages billions of lines of code in one monorepo
Sep 04, 2026
Transactional Outbox Pattern: Never Lose an Event Again
Apr 07, 2026
Cursor Skills: How to Create and Use Agent Skills
Jun 23, 2026
Git Flow vs GitHub Flow
Jun 05, 2026
Key Takeaways
- Annotations are labels, not executable logic. Something else must consume them.
@Retention(RetentionPolicy.RUNTIME)is required if you will read the annotation with reflection. The default is CLASS, which is invisible at runtime.@Targetlimits the annotation to types, methods, fields, parameters, and so on.- Members look like methods and may return primitives, String, Class, enums, annotations, or arrays of those types.
How It Works
- You declare
@interface MyTestand add meta-annotations for retention and target. - You put
@MyTeston a method, class, or field. - At compile time a processor may generate code, or at runtime reflection calls
isAnnotationPresentandgetAnnotation. - The JVM stores RUNTIME annotations with class metadata that the class loader built from bytecode.
Where It Is Used
- JUnit uses
@Testto discover test methods without a hardcoded list. - Spring, Jackson, Hibernate, and Bean Validation all drive behavior from annotations.
- Lombok and MapStruct use SOURCE retention so the annotation disappears after code generation.