What are annotations in Java, and what purpose do they serve?
Short answer
Annotations are a form of metadata that attach information to Java code elements (classes, methods, fields, parameters) without directly affecting program logic -- they're read by the compiler, tools, or the runtime via reflection to influence behavior, such as @Override…
Advertisement
AModel answer
Annotations are a form of metadata that attach information to Java code elements (classes, methods, fields, parameters) without directly affecting program logic -- they're read by the compiler, tools, or the runtime via reflection to influence behavior, such as @Override triggering a compile-time check, or @Entity marking a class for an ORM framework to map to a database table.
@Override
public String toString() {
return "MyObject";
}
@Deprecated
public void oldMethod() { }
@SuppressWarnings("unchecked")
public void legacyCode() { }Real-world example
A Spring Boot application uses @RestController and @GetMapping annotations to declaratively wire up HTTP routes to Java methods, letting the framework read this metadata at startup to build the routing table without any manual registration code.
Likely follow-ups
- What's the difference between a marker annotation (no elements) and one with elements?
- How does the compiler use @Override to catch a common class of bugs?
Related topics