Java Annotations: Basics of @ Metadata in Java
Java annotations are labels that start with @ and attach extra information, called metadata, to classes, methods, fields, parameters and other parts of your code. An annotation does not change what the code does by itself. Instead, a tool reads it: the compiler, a build-time processor, or your program at runtime through reflection.
You have already used Java annotations in this tutorial: @Override in method overriding, @FunctionalInterface with lambdas, and @Entity and @Id in the JPA lessons. This lesson explains how annotations work underneath: the syntax, where you can place them, who reads them, and how long they survive.
What a Java Annotation Looks Like
Every annotation is the @ sign followed by the name of an annotation type, optionally with values in parentheses.
@AnnotationName
@AnnotationName(value)
@AnnotationName(elementOne = value1, elementTwo = value2)
Start with the annotation you know best, @Override:
public class FirstAnnotation {
static class Animal {
String sound() {
return "...";
}
}
static class Dog extends Animal {
@Override // annotation on a method
String sound() {
return "Woof";
}
}
public static void main(String[] args) {
Animal pet = new Dog();
System.out.println(pet.sound());
}
}
Output:
Woof
How it works:
@Overridesits directly before the method it describes. By convention it goes on its own line.- The program prints
Woofwith or without the annotation. The annotation only tells the compiler, "I intend this method to override one from the parent class." - Annotations have no effect on how the method runs. Their value comes from whoever reads them.
Why the Compiler Reads @Override
Make a typo in the method name and the annotation catches it:
public class Typo {
static class Animal {
String sound() { return "..."; }
}
static class Cat extends Animal {
@Override
String sounds() { // typo: "sounds" instead of "sound"
return "Meow";
}
}
}
Typo.java:7: error: method does not override or implement a method from a supertype
@Override
^
1 error
Without @Override, sounds() would compile as a brand-new method, and Cat would silently inherit "..." from Animal. The annotation turns a hidden logic bug into a compile error.
Annotation Syntax: Marker, Single-Value and Full Forms
Annotations come in three shapes, depending on how many elements (named values) they have.
| Form | Example | When it is used |
|---|---|---|
| Marker | @Override, @Deprecated | No values; the presence of the annotation is the information |
| Single value | @SuppressWarnings("unchecked") | One element named value, so the name can be left out |
| Named elements | @Deprecated(since = "2.0", forRemoval = true) | One or more name = value pairs |
| Array value | @SuppressWarnings({"unchecked", "rawtypes"}) | An element that holds several values, written in { } |
import java.util.ArrayList;
import java.util.List;
public class Forms {
@Deprecated // marker annotation: no elements
static void oldPrint(String text) {
System.out.println(text);
}
@SuppressWarnings("unchecked") // single value
static List<String> copy(List rawList) {
return new ArrayList<>(rawList);
}
@Deprecated(since = "2.0", forRemoval = true) // named elements
static void legacyExport() {
System.out.println("exporting...");
}
@SuppressWarnings({"unchecked", "rawtypes"}) // array value
public static void main(String[] args) {
List raw = new ArrayList();
raw.add("Java");
System.out.println(copy(raw));
}
}
Output:
[Java]
How it works:
@SuppressWarnings("unchecked")is short for@SuppressWarnings(value = "unchecked"). The shortcut works only when the element is namedvalue.@Deprecatedand@Deprecated(since = "2.0", forRemoval = true)are the same annotation type. Its elements have default values, so you may leave them out.{"unchecked", "rawtypes"}passes an array. For a single item you can drop the braces:"unchecked"and{"unchecked"}mean the same.@SuppressWarningshides only the warning names you list.copysuppresses"unchecked", so compiling with-Xlint:allstill reports its rawListparameter as[rawtypes].mainlists both names, so nothing is reported there.
Note: Element values must be compile-time constants: literals,
static finalconstants, enum values, class literals such asString.class, other annotations, or arrays of these. A method call likeLocalDate.now()is not allowed.
Where You Can Place Java Annotations
Annotations can go on almost every declaration in Java. Each annotation type decides which places it allows; you will set that yourself in Java Custom Annotations.
import java.util.List;
@SuppressWarnings("unused") // on a class
public class Placement {
@Deprecated // on a field
private int legacyCounter;
@Deprecated // on a constructor
public Placement() { }
public void greet(@SuppressWarnings("unused") String name) { // on a parameter
@SuppressWarnings("unused") // on a local variable
List<String> tags = List.of("java", "basics");
System.out.println("Annotations do not change what this method does.");
}
public static void main(String[] args) {
new Placement().greet("Asha");
}
}
Output:
Annotations do not change what this method does.
| Location | Example |
|---|---|
| Class, interface, enum, record | @Entity public class Book { } |
| Field | @Id private Long id; |
| Method | @Override public String toString() |
| Constructor | @Deprecated public Placement() |
| Parameter | void save(@NotNull String name) |
| Local variable | @SuppressWarnings("unused") int temp = 0; |
| Package | in package-info.java: @Deprecated package com.gocourse.old; |
| Module | in module-info.java: @Deprecated module com.gocourse.legacy { } |
| Type use (Java 8+) | List<@NonNull String> names |
How it works:
- An annotation applies to the declaration that immediately follows it. Modifiers such as
publicandprivatecan come before or after it, but placing annotations first is the standard style. - You can stack several annotations on one declaration, each on its own line.
- Type-use annotations attach to a use of a type rather than a declaration. They are mostly read by checking tools such as nullness checkers.
Who Reads Java Annotations?
Because annotations do nothing on their own, it helps to know who consumes them. There are three readers.
| Reader | When | Examples |
|---|---|---|
| The compiler | During javac | @Override causes errors, @Deprecated causes warnings, @SuppressWarnings hides warnings |
| Annotation processors | During javac, as plug-ins | Lombok generates getters, MapStruct generates mappers, Hibernate generates metamodel classes |
| Your running program | At runtime, through reflection | JUnit finds @Test methods, Spring finds @Autowired fields, JPA reads @Entity and @Column |
The JPA lesson used the third kind: Hibernate reads @Entity, @Id and @Column at runtime to map objects to tables. Frameworks read annotations through the Java Reflection API, and so can your own code.
Retention: How Long an Annotation Survives
Not every annotation is still there when the program runs. Each annotation type has a retention policy that decides how far it travels.
| Retention | Kept in .java source | Kept in .class file | Visible at runtime | Example |
|---|---|---|---|---|
SOURCE | Yes | No | No | @Override, @SuppressWarnings |
CLASS (default) | Yes | Yes | No | Many bytecode-tool annotations |
RUNTIME | Yes | Yes | Yes | @Deprecated, @FunctionalInterface, JPA's @Entity |
You can see the difference with reflection. getAnnotations() returns every annotation that survived until runtime:
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
public class ReadAtRuntime {
static class Report {
@Override
public String toString() {
return "Report";
}
@Deprecated(since = "1.5")
public void printOld() { }
public void printNew() { }
}
public static void main(String[] args) throws NoSuchMethodException {
for (String methodName : new String[] {"toString", "printOld", "printNew"}) {
Method method = Report.class.getMethod(methodName);
Annotation[] annotations = method.getAnnotations();
System.out.println(methodName + " -> " + Arrays.toString(annotations));
}
Deprecated info = Report.class.getMethod("printOld").getAnnotation(Deprecated.class);
System.out.println("since = " + info.since() + ", forRemoval = " + info.forRemoval());
}
}
Output:
toString -> []
printOld -> [@java.lang.Deprecated(forRemoval=false, since="1.5")]
printNew -> []
since = 1.5, forRemoval = false
How it works:
toString()clearly has@Overridein the source, yet reflection returns an empty array.@OverridehasSOURCEretention, so the compiler throws it away after checking it.@DeprecatedhasRUNTIMEretention, so it is stored in the.classfile and reflection can see it, including the default valueforRemoval=falsethat was never written.getAnnotation(Deprecated.class)returns the annotation as an object. You call its elements like methods:info.since()andinfo.forRemoval().
You can confirm that the annotation lives in the bytecode with javap:
javap -v 'ReadAtRuntime$Report.class' | grep RuntimeVisibleAnnotations
#17 = Utf8 RuntimeVisibleAnnotations
RuntimeVisibleAnnotations:
An Annotation Type Is a Special Interface
Every annotation you use is declared somewhere with the keyword @interface. This is how the JDK declares the two annotations used above (comments removed):
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.SOURCE)
public @interface Override {
}
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(value = {CONSTRUCTOR, FIELD, LOCAL_VARIABLE, METHOD, PACKAGE, MODULE, PARAMETER, TYPE})
public @interface Deprecated {
String since() default "";
boolean forRemoval() default false;
}
How it works:
@interfacedeclares an annotation type. Its "methods", such assince(), are the elements you fill in when you write@Deprecated(since = "2.0").default ""anddefault falseare why@Deprecatedcan be used with no values.@Targetlimits where the annotation may be placed.@Overrideallows only methods, which is why putting it on a field is a compile error.@Retentionsets the retention policy from the table above. Annotations that describe other annotations, like@Targetand@Retention, are called meta-annotations. The next lesson, Java Built-in Annotations, covers each of them.
Real-World Example: An API Deprecation Report
Large codebases mark old methods with @Deprecated and plan to remove them. Because @Deprecated is kept at runtime, a short tool can scan a class and list what needs attention before the next release.
The service class being audited:
public class PaymentService {
public String payWithUpi(double amount) {
return "UPI payment of Rs. " + amount;
}
@Deprecated(since = "3.0")
public String payWithCheque(double amount) {
return "Cheque payment of Rs. " + amount;
}
@Deprecated(since = "2.4", forRemoval = true)
public String payWithDemandDraft(double amount) {
return "DD payment of Rs. " + amount;
}
public String refund(String orderId) {
return "Refund started for " + orderId;
}
}
The report tool:
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
public class DeprecationReport {
public static void main(String[] args) {
printReport(PaymentService.class);
}
static void printReport(Class<?> apiClass) {
System.out.println("API report for " + apiClass.getSimpleName());
System.out.printf("%-20s %-12s %-6s %s%n", "Method", "Status", "Since", "Action");
Method[] methods = apiClass.getDeclaredMethods();
Arrays.sort(methods, Comparator.comparing(Method::getName));
int deprecatedCount = 0;
for (Method method : methods) {
Deprecated deprecated = method.getAnnotation(Deprecated.class); // null if absent
if (deprecated == null) {
System.out.printf("%-20s %-12s %-6s %s%n", method.getName(), "active", "-", "keep using");
continue;
}
deprecatedCount++;
String action = deprecated.forRemoval() ? "REMOVE before next release" : "migrate when possible";
String since = deprecated.since().isEmpty() ? "?" : deprecated.since();
System.out.printf("%-20s %-12s %-6s %s%n", method.getName(), "deprecated", since, action);
}
System.out.println(deprecatedCount + " of " + methods.length + " methods are deprecated.");
}
}
javac PaymentService.java DeprecationReport.java
java DeprecationReport
Output:
API report for PaymentService
Method Status Since Action
payWithCheque deprecated 3.0 migrate when possible
payWithDemandDraft deprecated 2.4 REMOVE before next release
payWithUpi active - keep using
refund active - keep using
2 of 4 methods are deprecated.
The same annotations also warn every developer who still calls the old methods. Compile a class that uses all three payment methods:
public class Shop {
public static void main(String[] args) {
PaymentService payments = new PaymentService();
System.out.println(payments.payWithUpi(499.0));
System.out.println(payments.payWithCheque(1200.0));
System.out.println(payments.payWithDemandDraft(5000.0));
}
}
javac -Xlint:deprecation Shop.java
Shop.java:5: warning: [deprecation] payWithCheque(double) in PaymentService has been deprecated
System.out.println(payments.payWithCheque(1200.0));
^
Shop.java:6: warning: [removal] payWithDemandDraft(double) in PaymentService has been deprecated and marked for removal
System.out.println(payments.payWithDemandDraft(5000.0));
^
2 warnings
How it works:
- One annotation, two readers. The compiler reads
@Deprecatedto produce warnings, and the report tool reads the same annotation at runtime through reflection. getAnnotationreturnsnullwhen absent. That is how the loop separates active methods from deprecated ones.- Elements carry real data.
since()andforRemoval()turn a simple label into a migration plan:forRemoval = truebecomes "REMOVE before next release". - Sorted output.
getDeclaredMethods()returns methods in no fixed order, so the tool sorts them by name for a stable report. - Warning levels. A
forRemoval = truemethod produces a[removal]warning on every compile. Plain deprecation warnings appear in full only with-Xlint:deprecation; without it,javacprints a short note instead. - Behaviour is unchanged. Running
Shopstill prints all three payment lines. The annotations inform people and tools; they never block the call.