Annotations
An annotation is a label you attach to code that carries information about it without changing what it does. Tools, compilers, and frameworks read those labels and act on them.
Detailed Explanation
Start with what an annotation is not. Writing @Transactional on a method does not, by itself, open a database transaction. The annotation is inert. Something else has to look for it and do the work: the compiler, an annotation processor at build time, or a framework at runtime.
Before annotations arrived in Java 5, this metadata lived in two awkward places. One was XML. Early Spring and every servlet application described their wiring in files like web.xml, kept in a separate directory from the code they described, with no compiler checking that the class names were even spelled right. The other was marker interfaces: Serializable declares no methods, it exists only so code can test instanceof Serializable. Annotations gave the information a home next to the code it describes.
The single most important thing to learn about an annotation is its retention policy, because it decides who can ever see it.
| Retention | Kept until | Typical use |
|---|---|---|
SOURCE | Discarded by the compiler | @Override, @SuppressWarnings, Lombok |
CLASS | Stored in the class file, not loaded | Bytecode tools, the default |
RUNTIME | Readable through reflection | Spring, JPA, Jackson, JUnit |
The default is CLASS, which surprises people: write a custom annotation without specifying retention and your reflection code will never find it.
The built-in ones you meet first are compiler helpers. @Override makes the compiler verify that you really are overriding something, which catches the classic typo where you write equals(MyType other) and accidentally overload instead of override. @FunctionalInterface fails the build if the interface ever gains a second abstract method. @Deprecated produces a warning at every call site. All three trade nothing at runtime for real safety at compile time.
Custom annotations are declared with @interface. Their members look like methods but behave like named attributes, and each may have a default. The allowed types are deliberately narrow: primitives, String, Class, enums, other annotations, and arrays of those. Everything must be a compile-time constant, because the value is baked into the class file.
Two consumers matter in practice. Annotation processors run during compilation, read the annotated source tree, and generate more source. Lombok, Dagger, MapStruct, and the JPA metamodel all work this way, and their runtime cost is zero because the work happened at build time. Reflection-based frameworks instead scan classes at startup and build their wiring in memory. That is more flexible and it is why Spring can autowire something it has never seen, but it costs startup time, it defeats static analysis, and it is the main reason a Spring application takes seconds to boot while its generated-code equivalents take milliseconds.
Java 8 added two refinements worth knowing for interviews: repeatable annotations, so you can apply the same one twice, and type annotations, which can appear anywhere a type appears, enabling checkers like @NonNull String. Ahead-of-time compilation with GraalVM has pushed the ecosystem back towards build-time processing, since runtime reflection needs explicit configuration in a native image.
Code Examples
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method;
// RUNTIME retention is what makes this visible to reflection at all.
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD) // applying it to a field would not compile
@interface Audited {
String action(); // no default, so callers must supply it
boolean sensitive() default false; // has a default, so it is optional
}
public class AuditDemo {
@Audited(action = "TRANSFER_FUNDS", sensitive = true)
public void transfer(long amountInCents) {
// the annotation does nothing on its own; the scanner below is the behaviour
}
public void ping() {
}
public static void main(String[] args) {
for (Method method : AuditDemo.class.getDeclaredMethods()) {
Audited audited = method.getAnnotation(Audited.class); // null when absent
if (audited != null) {
System.out.println(method.getName()
+ " -> " + audited.action()
+ " sensitive=" + audited.sensitive());
}
}
// prints: transfer -> TRANSFER_FUNDS sensitive=true
}
}Built-in annotations that cost nothing at runtime and catch real bugs.
// Built-in annotations that cost nothing at runtime and catch real bugs.
@FunctionalInterface // build fails if a second abstract method is ever added
interface RetryPolicy {
boolean shouldRetry(int attempt);
}
class HttpClient {
String describe() {
return "plain client";
}
}
class RetryingHttpClient extends HttpClient {
@Override // build fails if the parent method is renamed or removed
String describe() {
return "retrying client";
}
}Common Gotchas
The default retention is CLASS, not RUNTIME
a custom annotation without `@Retention(RetentionPolicy.RUNTIME)` is invisible to `getAnnotation`, and your framework code will silently do nothing. This is the most common cause of "my annotation is being ignored".
Annotation members accept only compile-time constants
you cannot pass a `List`, an arbitrary object, or the result of a method call. Use a `Class` literal or a `String` and resolve it later.
Runtime annotation scanning is not free
reflective classpath scanning at startup costs real milliseconds per thousand classes, and it hides dependencies from the compiler and from your IDE's "find usages". Prefer build-time processing when startup latency or native images matter.
Meta-annotations are annotations on annotations
`@Retention`, `@Target`, `@Inherited`, and `@Documented` configure your annotation itself, which is why they look recursive the first time you see them.