All topics
library
intermediate

Annotations & Custom Annotations

Understand built-in annotations, create custom ones, and know the retention policies.

Annotations are metadata attached to code elements (classes, methods, fields, parameters). They don't change program behavior directly but are processed by the compiler, build tools, or frameworks at compile time or runtime.

Annotations = sticky notes on your code. Some notes are for the compiler (removed after reading), others stay attached forever (RUNTIME) for frameworks to read at startup.

Key Concepts

1
Built-in annotations: - @Override — compiler checks for valid override - @Deprecated — marks code as deprecated; compiler warns on usage - @SuppressWarnings — suppresses specific compiler warnings - @FunctionalInterface — compiler ensures exactly one abstract method - @SafeVarargs — suppresses heap pollution warnings for varargs
2
Meta-annotations (annotations on annotations): - @Retention — when the annotation is available: SOURCE (compiler only), CLASS (bytecode but not runtime), RUNTIME (available via reflection) - @Target — where it can be applied: TYPE, METHOD, FIELD, PARAMETER, etc. - @Documented — include in Javadoc - @Inherited — subclass inherits the annotation from parent class - @Repeatable — can be applied multiple times to the same element
3
Custom annotations are defined with @interface. Elements look like methods but are really named values. They can have default values. At runtime, annotations are accessed via reflection (Method.getAnnotation(), Class.getAnnotations(), etc.).
4
Frameworks like Spring, JPA, and Jackson use annotations extensively for configuration-over-convention.