Java Built-in Annotations: @Override, @Deprecated, @SuppressWarnings and Meta-Annotations
A practical guide to Java's standard annotations: @Override, @Deprecated with since and forRemoval, @SuppressWarnings, @SafeVarargs, @FunctionalInterface, @Serial and @Generated, plus the meta-annotations @Target, @Retention, @Documented, @Inherited and @Repeatable.
kvi5hnuCode Sprout team member9 min readOn this page
Before writing annotation tools of your own, get to know the annotations that ship with Java. You'll use some of them every day. They live in java.lang, java.lang.annotation and javax.annotation.processing. A few are meta-annotations that describe other annotations. The rest annotate ordinary code, mostly to make the compiler check or relax something.
| Annotation | Applicable to | Purpose |
|---|---|---|
@Override | methods | checks that the method overrides a supertype method |
@Serial | methods, fields | checks that a serialization member is declared correctly (Java 14) |
@Deprecated | almost all declarations | marks an item whose use is discouraged |
@SuppressWarnings | declarations | suppresses compiler warnings of the given kinds |
@SafeVarargs | methods and constructors | asserts that a generic varargs parameter is used safely |
@FunctionalInterface | interfaces | marks an interface as functional (exactly one abstract method) |
@Generated | all declarations | marks source code produced by a tool |
@Target | annotations | where the annotation can be applied |
@Retention | annotations | how long the annotation is retained |
@Documented | annotations | the annotation appears in documentation of annotated items |
@Inherited | annotations | a class annotation is inherited by subclasses |
@Repeatable | annotations | the annotation can be applied several times to one item |
Annotations for compilation
@Override
@Override makes the compiler verify that the method really overrides (or implements) a method of a supertype. It catches one of the most common bugs in Java:
public class Point {
@Override public boolean equals(Point other) { ... } // ERROR
}
This equals overloads instead of overriding, because Object.equals takes an Object parameter, not a Point. Without the annotation, the program compiles, and HashSet, List.contains and friends silently use the inherited Object.equals. With it, compilation fails. Put @Override on every overriding method. IDEs add it automatically.
@Deprecated
@Deprecated marks items whose use is no longer encouraged, and the compiler warns when you use them. It plays the same role as the @deprecated Javadoc tag, but it's kept until runtime, so tools can find it through reflection. Since Java 9, it has two elements:
/** @deprecated use {@link #distanceTo(Point)} instead */
@Deprecated(since = "2.0", forRemoval = true)
double dist(Point p) { ... }
sincerecords the version in which the item became deprecated.forRemoval = trueannounces that it will be deleted in a future version. The compiler then issues a stronger, "removal" warning that is on by default.
Write both the annotation (for tools) and the Javadoc tag (to explain what to use instead). The JDK's jdeprscan tool scans JAR files for uses of deprecated JDK APIs, which helps before an upgrade.
@SuppressWarnings
@SuppressWarnings tells the compiler to stay quiet about a particular category of warning:
@SuppressWarnings("unchecked")
T[] result = (T[]) Array.newInstance(cl, n);
Common keys are "unchecked", "rawtypes", "deprecation", "removal", "serial", "fallthrough", "unused" (IDE) and "this-escape" (Java 21). Apply it to the smallest possible scope, preferably a single local variable declaration as above, rather than a whole class. Add a comment explaining why the suppressed operation is safe.
@SafeVarargs
A method with a generic varargs parameter (T... items) triggers "possible heap pollution" warnings, because the parameter is really an array of an erased type (article 80). @SafeVarargs asserts that the method doesn't corrupt that array: it only reads it, doesn't store into it, and doesn't let it escape. It's allowed only on methods that can't be overridden, which means static, final or private methods and constructors. The demo's listOf is safe because it only reads the elements.
@FunctionalInterface
@FunctionalInterface (article 60) documents that an interface is a target for lambda expressions, and makes the compiler check that it has exactly one abstract method:
@FunctionalInterface
public interface IntFunction<R> {
R apply(int value);
}
If someone later adds a second abstract method, compilation fails. Use it only for interfaces that conceptually are functions. AutoCloseable happens to have one abstract method but isn't meant as a function type, so it isn't annotated.
@Serial
@Serial (Java 14) marks the special serialization members such as serialVersionUID, writeObject, readObject, writeReplace and readResolve. They aren't declared in any interface, so a typo or a wrong signature would otherwise go unnoticed. With -Xlint:serial, the compiler checks that each @Serial member has the correct name and signature.
@Generated
javax.annotation.processing.Generated marks code produced by a code generator. Editors can then hide it, and the generator can find and delete its older output. It must contain a unique identifier for the generator, and may add an ISO 8601 date and a comment:
@Generated(value = "com.example.generator", date = "2025-01-04T12:08:56.235-07:00")
Its retention is SOURCE. It lives in the java.compiler module.
Meta-annotations
@Target and @Retention were covered in article 106. The JDK also has a small @Native annotation (SOURCE retention, on fields), which marks constants that native code refers to, so header-generating tools include them.
@Documented
@Documented is a hint to documentation tools such as Javadoc. A documented annotation is shown in the documentation of every item it annotates, just like modifiers such as public or static. Other annotations are left out.
The choice depends on whether the annotation matters to users of the API. @FunctionalInterface is documented, because callers want to know they can pass a lambda. @SuppressWarnings isn't, because it's an implementation detail that is of no interest to someone reading the Javadoc.
@Inherited
@Inherited applies only to annotations on classes. If a class has an inherited annotation, all its subclasses automatically have it as well. That makes annotations work like marker interfaces such as Serializable:
@Inherited @interface Persistent { }
@Persistent class Employee { ... }
class Manager extends Employee { ... } // also @Persistent
Mind the limits. Inheritance works only from superclasses: annotations on interfaces are never inherited, and neither are annotations on methods or fields. Reflection respects it too. getAnnotation and isAnnotationPresent see inherited annotations, but getDeclaredAnnotation only sees annotations written on the class itself.
@Repeatable
@Repeatable lets an annotation be used several times on the same item, as with JUnit's @Tag:
@Tag("localized")
@Tag("showstopper")
void testHello() { ... }
For historical reasons, the class file format allows one annotation of each type per item. The author of a repeatable annotation must therefore also supply a container annotation whose value element is an array of the repeated annotation, and name it in @Repeatable:
@Repeatable(Tags.class)
@interface Tag { String value(); }
@interface Tags { Tag[] value(); }
The container must have the same or a longer retention, and targets compatible with the repeated annotation.
When an item carries two or more @Tags, the compiler wraps them into one @Tags annotation. A single @Tag is stored as is. That complicates processing:

getAnnotation(Tag.class)finds a lone tag but returnsnullwhen there are several, because they are hidden inside@Tags.getAnnotation(Tags.class)finds the container only when there are several.getAnnotationsByType(Tag.class)looks through the container and returns all tags in both cases. Use it for repeatable annotations. Article 108 covers this further.
A complete example
The demo puts each compile-time annotation where it belongs and prints the retention of each standard annotation, read through reflection from their own @Retention meta-annotations. It reads @Deprecated(since, forRemoval) at runtime, confirms that @Override is gone after compilation, and checks which annotations are @Documented. It also shows that @Inherited passes from Employee to Manager but not from an interface, and how one versus two @Tags are stored.
import java.io.*;
import java.lang.annotation.*;
import java.lang.reflect.*;
import java.util.*;
public class Solution {
// ---------- annotations for compilation ----------
static class Point implements Serializable {
@Serial private static final long serialVersionUID = 1L;
final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override public boolean equals(Object other) { // really overrides Object.equals
return other instanceof Point p && x == p.x && y == p.y;
}
@Override public int hashCode() { return Objects.hash(x, y); }
/** @deprecated use {@link #distanceTo(Point)} */
@Deprecated(since = "2.0", forRemoval = true)
double dist(Point p) { return distanceTo(p); }
double distanceTo(Point p) { return Math.hypot(x - p.x, y - p.y); }
@Serial private void writeObject(ObjectOutputStream out) throws IOException { out.defaultWriteObject(); }
}
@SafeVarargs
static <T> List<T> listOf(T... items) { // only reads the array: safe
var result = new ArrayList<T>();
for (T item : items) result.add(item);
return result;
}
@SuppressWarnings("unchecked")
static <T> T[] newArray(Class<T> cl, int n) { return (T[]) Array.newInstance(cl, n); }
@FunctionalInterface
interface IntFn<R> { R apply(int value); }
// ---------- meta-annotations ----------
@Documented @Retention(RetentionPolicy.RUNTIME) @interface Stable {}
@Inherited @Retention(RetentionPolicy.RUNTIME) @interface Persistent {}
@Retention(RetentionPolicy.RUNTIME) @interface NotInherited {}
@Persistent @NotInherited static class Employee {}
static class Manager extends Employee {} // inherits @Persistent only
@Persistent interface Auditable {}
static class Invoice implements Auditable {} // @Inherited ignores interfaces
@Repeatable(Tags.class) @Retention(RetentionPolicy.RUNTIME) @interface Tag { String value(); }
@Retention(RetentionPolicy.RUNTIME) @interface Tags { Tag[] value(); }
static class Tests {
@Tag("fast") void one() {}
@Tag("localized") @Tag("showstopper") void two() {}
}
public static void main(String[] args) throws Exception {
System.out.println("-- compile-time annotations in action --");
var p = new Point(0, 0);
System.out.println(" equals overrides Object.equals: " + p.equals(new Point(0, 0)));
System.out.println(" listOf: " + listOf("a", "b") + ", newArray length: " + newArray(String.class, 3).length);
IntFn<String> stars = n -> "*".repeat(n);
System.out.println(" functional interface: " + stars.apply(3));
System.out.println("-- which standard annotations are kept at runtime? --");
for (Class<? extends Annotation> a : List.of(Override.class, Deprecated.class, SuppressWarnings.class,
SafeVarargs.class, FunctionalInterface.class, Serial.class, Documented.class, Inherited.class,
Repeatable.class, Target.class, Retention.class, Native.class)) {
Retention r = a.getAnnotation(Retention.class);
System.out.printf(" %-21s %s%n", "@" + a.getSimpleName(), r.value());
}
System.out.println("-- reading @Deprecated --");
Deprecated dep = Point.class.getDeclaredMethod("dist", Point.class).getAnnotation(Deprecated.class);
System.out.println(" dist: since=" + dep.since() + ", forRemoval=" + dep.forRemoval());
System.out.println(" @Override visible at runtime: "
+ Point.class.getDeclaredMethod("equals", Object.class).isAnnotationPresent(Override.class));
System.out.println(" IntFn is marked functional: " + IntFn.class.isAnnotationPresent(FunctionalInterface.class));
System.out.println("-- @Documented --");
System.out.println(" Stable documented: " + Stable.class.isAnnotationPresent(Documented.class)
+ ", FunctionalInterface documented: " + FunctionalInterface.class.isAnnotationPresent(Documented.class)
+ ", SuppressWarnings documented: " + SuppressWarnings.class.isAnnotationPresent(Documented.class));
System.out.println("-- @Inherited --");
System.out.println(" Manager has @Persistent: " + Manager.class.isAnnotationPresent(Persistent.class)
+ ", declared on Manager itself: " + (Manager.class.getDeclaredAnnotation(Persistent.class) != null));
System.out.println(" Manager has @NotInherited: " + Manager.class.isAnnotationPresent(NotInherited.class));
System.out.println(" Invoice (implements @Persistent interface) has it: " + Invoice.class.isAnnotationPresent(Persistent.class));
System.out.println("-- @Repeatable and the container --");
for (String name : List.of("one", "two")) {
Method m = Tests.class.getDeclaredMethod(name);
System.out.println(" " + name + "(): getAnnotation(Tag)=" + (m.getAnnotation(Tag.class) != null)
+ ", getAnnotation(Tags)=" + (m.getAnnotation(Tags.class) != null)
+ ", getAnnotationsByType(Tag)=" + Arrays.stream(m.getAnnotationsByType(Tag.class)).map(Tag::value).toList());
}
}
}
-- compile-time annotations in action --
equals overrides Object.equals: true
listOf: [a, b], newArray length: 3
functional interface: ***
-- which standard annotations are kept at runtime? --
@Override SOURCE
@Deprecated RUNTIME
@SuppressWarnings SOURCE
@SafeVarargs RUNTIME
@FunctionalInterface RUNTIME
@Serial SOURCE
@Documented RUNTIME
@Inherited RUNTIME
@Repeatable RUNTIME
@Target RUNTIME
@Retention RUNTIME
@Native SOURCE
-- reading @Deprecated --
dist: since=2.0, forRemoval=true
@Override visible at runtime: false
IntFn is marked functional: true
-- @Documented --
Stable documented: true, FunctionalInterface documented: true, SuppressWarnings documented: false
-- @Inherited --
Manager has @Persistent: true, declared on Manager itself: false
Manager has @NotInherited: false
Invoice (implements @Persistent interface) has it: false
-- @Repeatable and the container --
one(): getAnnotation(Tag)=true, getAnnotation(Tags)=false, getAnnotationsByType(Tag)=[fast]
two(): getAnnotation(Tag)=false, getAnnotation(Tags)=true, getAnnotationsByType(Tag)=[localized, showstopper]
Common questions
Should I always write @Override?
Yes. It costs nothing, and the compiler then catches methods that overload instead of overriding, such as equals(Point) instead of equals(Object). IDEs add it automatically.
What does @Deprecated(forRemoval = true) mean for my code?
The API will be deleted in a future release. The compiler issues a "removal" warning that is on by default. Plan a migration, and run jdeprscan on your JARs before upgrading the JDK.
Is @FunctionalInterface required for lambdas?
No. Any interface with exactly one abstract method can be a lambda target. The annotation documents the intent and makes the compiler check the rule, so nobody accidentally adds a second abstract method.
Why does getAnnotation return null for my repeated annotation?
When an annotation appears more than once, the compiler wraps the repeats in the container annotation. Use getAnnotationsByType, which finds the annotations whether they appear once or several times.
Are annotations on interfaces inherited by implementing classes?
No. @Inherited only works from superclass to subclass, and only for class-level annotations. Frameworks that need interface annotations look them up themselves.
API reference
java.lang.Deprecated (and related elements)
| Element | Description |
|---|---|
String since() default "" | version in which the item was deprecated (Java 9) |
boolean forRemoval() default false | true if the item is going to be removed (Java 9) |
java.lang.annotation.Repeatable, java.lang.reflect.AnnotatedElement
| Method | Description |
|---|---|
Class<? extends Annotation> Repeatable.value() | the container annotation type |
<A> A getAnnotation(Class<A> type) | the annotation of this type, including inherited ones; null for multiple repeats |
<A> A getDeclaredAnnotation(Class<A> type) | like getAnnotation, ignoring inherited annotations |
<A> A[] getAnnotationsByType(Class<A> type) | all annotations of this type, looking into containers |
boolean isAnnotationPresent(Class<? extends Annotation> type) | true if getAnnotation(type) is non-null |
Summary
@Overridecatches accidental overloading, so use it everywhere.@FunctionalInterfaceenforces a single abstract method, and@Serialchecks serialization members.@Deprecated(since, forRemoval)warns users, can be seen at runtime, and should come with a@deprecatedJavadoc tag.jdeprscanfinds uses of deprecated APIs.- Use
@SuppressWarningson the narrowest scope, with a reason. Use@SafeVarargsonly on non-overridable methods that don't misuse their generic varargs array. @Generatedmarks tool-generated source.- Of the meta-annotations,
@Documentedshows an annotation in Javadoc and@Inheritedpasses class annotations to subclasses (not from interfaces).@Repeatableneeds a container annotation, so read repeats withgetAnnotationsByType.
Practice Questions
What does @Override catch in "@Override public boolean equals(Point other)"?
The method doesn't override Object.equals(Object), because its parameter type is Point, so it only overloads equals. @Override turns that silent mistake into a compile-time error.
What is the difference between @Deprecated and @Deprecated(forRemoval = true)?
Both make the compiler warn about uses. forRemoval = true announces that the item will be deleted in a future release. That produces a separate, stronger "removal" warning, which is enabled by default and harder to ignore.
Why can't @SafeVarargs be placed on an ordinary public instance method?
An overriding method in a subclass could use the varargs array unsafely, so the promise couldn't be guaranteed. @SafeVarargs is only allowed on methods that can't be overridden (static, final or private) and on constructors.
Class Manager extends Employee, and Employee is annotated with @Persistent, which is @Inherited. What do getAnnotation and getDeclaredAnnotation return for Manager?
Manager.class.getAnnotation(Persistent.class) returns the inherited annotation. Manager.class.getDeclaredAnnotation(Persistent.class) returns null, because the annotation isn't written on Manager itself.
A method has two @Tag annotations. Why does getAnnotation(Tag.class) return null, and what should you call instead?
The compiler wrapped the two tags into the container annotation @Tags, so no direct @Tag exists on the method. Call getAnnotationsByType(Tag.class), which looks inside the container and returns both tags.
Previous: Defining Custom Java Annotations: @interface, Elements, Retention and Target
Next: Processing Java Annotations at Runtime with Reflection
Related reading
- Defining Custom Java Annotations: @interface, Elements, Retention and Target
- Java Annotations Explained: Syntax, Uses and Where You Can Annotate
- JShell Tutorial: Java's Interactive REPL for Quick Experiments
- Using a Java IDE: IntelliJ IDEA, VS Code and Eclipse for Beginners
- How to Compile and Run Java Programs from the Command Line

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.