Java Annotation
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.
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.