Skip to content
Tutorials Center
My learning

Topics

Lesson 154 of 201 ยท JVM and Advanced Topics

Annotations

Learn Java annotations - @Override, @Deprecated and friends, defining your own, retention and targets, repeatable and inherited annotations, and reading them at run time.

An annotation is a label you attach to a piece of code: a class, method, field, parameter, record component, even a type. It starts with @, and on its own it does nothing at all. Its power comes from who reads it. The compiler reads @Override and refuses to compile a method that doesn't really override anything. A test runner reads @Test and calls your method. Spring reads @Component and creates the object for you. Jackson reads @JsonProperty and renames a field in the JSON output.

Java
@Override
public String toString() {
    return "Order #" + id;
}

Annotations let tools and frameworks attach behavior to code without you writing glue code, and they keep that information right next to the code it describes. In this lesson you'll use the built-in annotations, define your own, control where they may appear and how long they survive, and read them at run time with reflection to build a small validation framework and a command router.

Built-in annotations

java.lang provides five annotations that every Java developer uses:

Annotation Put it on What it does
@Override Methods Compile error unless the method overrides or implements a supertype method
@Deprecated Almost anything Marks an API as discouraged; callers get a warning. Elements: since, forRemoval
@SuppressWarnings Declarations Silences named compiler warnings ("unchecked", "deprecation", "removal", ...) in that scope
@FunctionalInterface Interfaces Compile error unless the interface has exactly one abstract method
@SafeVarargs Final, static or private methods; constructors Promises a generic varargs method doesn't pollute the heap (see Type Erasure)

@Override catches mistakes you can't see

The classic bug: you mean to override equals(Object), but you write equals(Point). That's a brand-new overload, not an override, so HashSet and List.contains keep using Object.equals and silently compare identities. With @Override, the compiler catches it. This example fails to compile on purpose:

Java @Override turns a silent bug into a compile error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The compiler reports method does not override or implement a method from a supertype. Change the parameter to Object other and cast inside (or better, use a record, which writes equals for you). Put @Override on every overriding method, including interface implementations; IDEs add it automatically.

@Deprecated and @SuppressWarnings

@Deprecated tells callers "don't use this anymore." Since Java 9 it has two elements: since (the version that deprecated it) and forRemoval (true means it will be deleted, and callers get a stronger [removal] warning). Always say in the Javadoc what to use instead.

Java Deprecation warnings and how to silence one

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The program runs, and the compiler output under it shows one [removal] warning for the call on line 25. fromLegacyApi uses a raw List, which normally produces [unchecked] warnings, but @SuppressWarnings("unchecked") silences them for that one method. Remove the annotation and run again to see them appear.

Two habits keep suppression honest: put @SuppressWarnings on the smallest scope possible (a single method or even a single local variable declaration, never a whole class), and add a comment explaining why the warning is safe to ignore. (Uses of a deprecated member inside the same top-level class never warn, which is why TemperatureUtils is a separate class here.)

Annotation syntax

An annotation can have elements, which look like method calls with named arguments:

Java
@Deprecated(since = "17", forRemoval = true)       // named elements
@SuppressWarnings("unchecked")                      // single element named "value": name can be omitted
@SuppressWarnings({"unchecked", "rawtypes"})        // array value
@FunctionalInterface                                // marker annotation: no elements

Element values must be compile-time constants: literals, static final constants, enum constants, class literals like String.class, other annotations, or arrays of those. You can't pass a method call result or null:

Java
@Range(max = Integer.MAX_VALUE)        // OK: a constant
@Range(max = computeLimit())           // error: element value must be a constant expression
@Label(text = null)                    // error: null is never allowed

You can place annotations on declarations (classes, methods, fields, parameters, local variables, record components, packages in package-info.java, modules in module-info.java) and, since Java 8, on type uses, wherever a type appears:

Java
List<@NonNull String> names;                      // a type argument
String text = (@NonNull String) value;            // a cast
void process() throws @Critical IOException {}    // a throws clause

Type annotations like @NonNull don't do anything in plain Java; checkers such as the Checker Framework, NullAway or IDE inspections read them to find bugs at compile time.

Defining your own annotation

You declare an annotation type with @interface. Its elements are written like abstract methods, optionally with a default:

Java
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD, ElementType.TYPE})
public @interface Todo {
    String value();                         // required (no default)
    Priority priority() default Priority.MEDIUM;
    String[] assignees() default {};

    enum Priority { LOW, MEDIUM, HIGH }
}

@Todo(value = "Cache the results", priority = Todo.Priority.HIGH, assignees = {"amara", "luis"})
void loadCatalog() { ... }

Element types are limited to primitives, String, Class (including Class<? extends Something>), enums, other annotation types, and one-dimensional arrays of these. An element named value is special: if it's the only one you set, you may skip the name, as in @Todo("Cache the results").

Meta-annotations: @Retention and @Target

Annotations on annotation types are called meta-annotations. The two you'll write every time are:

@Retention decides how long the annotation survives:

Policy Kept in source Kept in .class file Visible to reflection Typical use
SOURCE yes no no Compiler hints and annotation processors (@Override, Lombok's @Getter)
CLASS (the default!) yes yes no Bytecode tools that read class files
RUNTIME yes yes yes Frameworks that read annotations while the program runs (JUnit, Spring, JPA, Jackson)

@Target lists where the annotation may appear: TYPE (classes, interfaces, enums, records), FIELD, METHOD, PARAMETER, CONSTRUCTOR, LOCAL_VARIABLE, ANNOTATION_TYPE, PACKAGE, TYPE_PARAMETER, TYPE_USE, MODULE and RECORD_COMPONENT. Putting the annotation anywhere else is a compile error. Without @Target, an annotation is allowed on almost every declaration (but not on type uses).

The default retention is the most common beginner bug with custom annotations: forget @Retention(RUNTIME) and your annotation compiles fine, sits in the class file, and is completely invisible to getAnnotation, which returns null.

Java Only RUNTIME annotations are visible to reflection

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

@Documented, @Inherited and @Repeatable

  • @Documented makes the annotation appear in the Javadoc of annotated elements.
  • @Inherited makes a class-level annotation apply to subclasses too. It only works for classes extending classes: it has no effect on interfaces, methods or fields.
  • @Repeatable(Container.class) (Java 8) lets you use the same annotation several times on one element. The compiler wraps the repetitions in a container annotation whose value() is an array.
Java Repeatable and inherited annotations

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Notice the trap in the second line of output: when an annotation is repeated, getAnnotation(Schedule.class) returns null, because the class file actually stores a single @Schedules container. Always read repeatable annotations with getAnnotationsByType, which looks inside the container (and also finds a single, unrepeated use).

Reading annotations at run time

Every reflective object that can carry annotations (Class, Method, Field, Constructor, Parameter, RecordComponent) implements AnnotatedElement, with these methods:

Method Returns
isAnnotationPresent(A.class) true if the annotation is present (including inherited ones)
getAnnotation(A.class) The annotation instance or null
getAnnotationsByType(A.class) An array; understands repeatable containers
getAnnotations() All present annotations, including @Inherited ones
getDeclaredAnnotation(A.class) / getDeclaredAnnotations() Only annotations written directly on this element

The object you get back implements your annotation interface, so you read its elements by calling them like methods: range.min(). Behind the scenes it's a dynamic proxy created by the JVM.

Example: a tiny validation framework

This is how Jakarta Bean Validation (@NotBlank, @Size, @Min in Spring and Hibernate) works at its core. The annotations only describe the rules; a validator reads them and checks the values:

Java Annotation-driven validation of records

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Adding a rule to a record is now one annotation, and validate works for any record. Notice the target: RECORD_COMPONENT keeps the annotation on the component itself. If you declare an annotation with @Target(ElementType.FIELD) and put it on a record component, Java copies it to the generated private field instead, so it's found with getDeclaredField(...) rather than getRecordComponents(). Annotations propagate to every place where their target allows (field, accessor method, constructor parameter), which is how libraries written for classes also work with records.

Example: routing commands to methods

Web frameworks map URLs to methods with annotations like @GetMapping("/books"). Here is the same idea for text commands typed into the Input box:

Java An annotation-based command router

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The router scans the class once at startup and stores the methods in a map, so each command is a fast map lookup plus a reflective call. Real frameworks do the same: scanning annotations is expensive, so they do it during startup and cache the results. getDeclaredMethods() returns methods in no particular order, which is why the routes go into a sorted TreeMap for the help text.

Annotations in the real world

You'll spend far more time using annotations than defining them. A taste of what's ahead in the Advanced Java track:

Java
@RestController                      // Spring: this class handles HTTP requests
@RequestMapping("/books")
class BookController {
    @GetMapping("/{id}")             // Spring: GET /books/42 calls this method
    Book find(@PathVariable long id) { ... }
}

@Entity @Table(name = "books")       // JPA: this class maps to a database table
class Book {
    @Id @GeneratedValue Long id;
    @Column(nullable = false) String title;
}

class BookTest {
    @Test                            // JUnit: run this method as a test
    void titleIsRequired() { ... }
}

There are two ways tools process annotations:

  1. At run time, with reflection (RUNTIME retention), as in the examples above. Spring, JPA, Jackson and JUnit work this way.
  2. At compile time, with an annotation processor (usually SOURCE retention). A processor is a class that javac runs while compiling; it can report errors or generate new source files. Lombok, MapStruct, Dagger, Micronaut and Immutables use this approach, which costs nothing at run time.

A processor skeleton looks like this (read-only: it runs inside javac, configured by your build tool):

Java
@SupportedAnnotationTypes("com.example.Todo")
@SupportedSourceVersion(SourceVersion.RELEASE_25)
public class TodoProcessor extends AbstractProcessor {
    @Override
    public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment round) {
        for (Element element : round.getElementsAnnotatedWith(Todo.class)) {
            processingEnv.getMessager().printMessage(
                Diagnostic.Kind.NOTE, "TODO: " + element.getAnnotation(Todo.class).value(), element);
        }
        return true;
    }
}

A few guidelines when you design your own annotations:

  • Prefer a plain method call or interface when it's clearer. Annotations hide control flow: a reader can't "jump to the code" that handles @Command.
  • Always set @Retention and @Target explicitly.
  • Give elements sensible defaults so the common case is just @MyAnnotation.
  • Validate annotation usage early (at startup or with a processor) and fail with a clear message.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. You define @interface Audit {} with no meta-annotations, put it on a class, and call MyClass.class.getAnnotation(Audit.class). What do you get?

    Without @Retention the policy is CLASS, so the annotation is in the class file but invisible to reflection. getAnnotation returns null.
  2. 2. A class is annotated with @Schedule(day = "Mon") and @Schedule(day = "Fri") where Schedule is @Repeatable. What does getAnnotation(Schedule.class) return?

    Repeated annotations are stored inside their container annotation, so a direct lookup for Schedule finds nothing. Use getAnnotationsByType(Schedule.class) to get both.
  3. 3. Which element declaration is NOT allowed in an annotation type?

    Elements may be primitives, String, Class, enums, annotations or one-dimensional arrays of those. List is not allowed; use String[] instead.
  4. 4. Interface Plugin is annotated with an @Inherited, RUNTIME annotation @Managed. Class Cache implements Plugin. What does Cache.class.isAnnotationPresent(Managed.class) return?

    @Inherited affects class annotations inherited from superclasses only. Annotations on implemented interfaces are never inherited.
  5. 5. What does @Override change about the compiled program when the method really does override?

    @Override has SOURCE retention. It only asks the compiler to verify that the method overrides something; the bytecode is identical without it.

Summary

  • Annotations attach metadata to code; they do nothing until the compiler, a tool or a framework reads them.
  • Use the built-ins: @Override everywhere it applies, @Deprecated(since, forRemoval) with a Javadoc replacement, narrowly scoped @SuppressWarnings, @FunctionalInterface and @SafeVarargs.
  • Define annotation types with @interface; elements are constants of limited types, may have defaults, and value can be set without its name.
  • @Retention controls lifetime (SOURCE, CLASS by default, RUNTIME for reflection); @Target controls placement, including TYPE_USE and RECORD_COMPONENT.
  • @Repeatable needs a container annotation; read repeated ones with getAnnotationsByType. @Inherited works only for class annotations from superclasses.
  • Reflection reads RUNTIME annotations via AnnotatedElement methods; frameworks scan once at startup and cache. Annotation processors handle SOURCE annotations at compile time and can generate code.

Next: Reflection, where you'll inspect and call classes, fields, methods and constructors at run time, the machinery behind every annotation-driven framework.