Chapter 65 of 77

Annotations in Java

You have already been using an annotation for a long time: @Override. When we put it above a method, the method's behaviour doesn't change at all. Instead, it is a note to the compiler that says "I intend to override a parent method; please check that I really do."

Think of annotations like sticky notes on a textbook page. The notes don't change what is printed on the page, but someone who reads them (you, a teacher, or a tool) can act on them. In Java, the "readers" are the compiler, build tools, and frameworks.

An annotation is a form of metadata (data about the code) that you attach to classes, methods, fields, parameters, and other parts of a program. It starts with the @ symbol. An annotation does nothing by itself; it only has an effect when the compiler, a tool, or code running at runtime reads it.

Annotations were added in Java 5. Today they are everywhere: testing tools like JUnit use @Test, and frameworks like Spring use annotations such as @Autowired to wire an application together. Understanding them is important for both interviews and real projects.

Annotation Syntax

An annotation is written with @ followed by its name, placed just before the thing it describes. Some annotations take values inside brackets:

@Override                                   // marker annotation: no values
public String toString() { ... }

@SuppressWarnings("unchecked")              // one value
static List<String> makeList() { ... }

@Deprecated(since = "2.0", forRemoval = true)   // named values
int oldMultiply(int a, int b) { ... }

The named values like since = "2.0" are called elements. If an annotation has an element called value and it is the only one you are setting, you can leave out the name: @SuppressWarnings("unchecked") is short for @SuppressWarnings(value = "unchecked").

Annotations can be placed on classes, interfaces, methods, constructors, fields, parameters, and local variables. You can also put several annotations on the same thing.

Built-in Annotations

Java comes with a few annotations that the compiler understands directly:

Annotation

Used on

What it does

@Override

Methods

Compile error if the method does not actually override or implement a parent method

@Deprecated

Almost anything

Marks code as outdated; the compiler warns anyone who uses it

@SuppressWarnings

Classes, methods, fields, variables

Tells the compiler to hide specific warnings

@FunctionalInterface

Interfaces

Compile error if the interface does not have exactly one abstract method

@SafeVarargs

Varargs constructors and static, final, or private varargs methods

Promises that a generic varargs method is safe, which hides a related warning

We covered @Override in detail in the Method Overriding chapter: it catches mistakes like a misspelled method name or wrong parameter types. You will meet @FunctionalInterface again in the Functional Interfaces chapter. Let's look at @Deprecated and @SuppressWarnings now.

@Deprecated

When a method is replaced by a better one, we can't just delete it, because other code may still be using it. Instead, we mark it @Deprecated. The code keeps working, but everyone who uses it gets a warning. Since Java 9, the annotation has two optional elements:

  • since: the version in which it was deprecated.

  • forRemoval: if true, it will be removed in a future version, so users should move away from it soon.

import java.util.ArrayList;
import java.util.List;

class Calculator {

    /** @deprecated use {@link #add(int, int)} instead */
    @Deprecated(since = "2.0")
    int sum(int a, int b) {
        return a + b;
    }

    @Deprecated(since = "2.0", forRemoval = true)
    int oldMultiply(int a, int b) {
        return a * b;
    }

    int add(int a, int b) {
        return a + b;
    }
}

class Main {

    @SuppressWarnings("unchecked")
    static List<String> makeList() {
        List raw = new ArrayList();   // raw type: normally gives an "unchecked" warning
        raw.add("Java");
        return raw;
    }

    public static void main(String[] args) {
        Calculator calc = new Calculator();
        System.out.println(calc.sum(2, 3));
        System.out.println(calc.oldMultiply(2, 3));
        System.out.println(calc.add(2, 3));
        System.out.println(makeList());
    }
}

When we compile this with a plain javac Main.java, the compiler prints:

Main.java:34: warning: [removal] oldMultiply(int,int) in Calculator has been deprecated and marked for removal
        System.out.println(calc.oldMultiply(2, 3));
                               ^
Note: Main.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
1 warning

The forRemoval = true method gets a full warning straight away. The normal deprecated method sum() only produces a short note; compiling with javac -Xlint:deprecation Main.java shows its warning too:

Main.java:33: warning: [deprecation] sum(int,int) in Calculator has been deprecated

These are only warnings, so the program still compiles and runs. Output:

5
6
5
[Java]

It is good practice to also write a @deprecated tag in the method's documentation comment (as we did for sum()) to tell users what to use instead. Note the difference: @Deprecated with a capital D is the annotation; @deprecated with a small d is a Javadoc tag inside a /** */ comment.

@SuppressWarnings

In the same program, makeList() uses a "raw" List, with no type in angle brackets, which throws away the type safety that generics give us (see the Generics chapter). Without the annotation, the compiler would print:

Note: Main.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.

@SuppressWarnings("unchecked") hides that warning for the method. Other common values are "deprecation", "removal", and "rawtypes", and you can pass several at once: @SuppressWarnings({"unchecked", "rawtypes"}).

Use it carefully. A warning usually points at a real risk, so suppress it only when you have checked the code and are sure it is safe, and put the annotation on the smallest piece of code possible (one method or one variable, not a whole class).

Creating Your Own Annotation

We can define our own annotations with the @interface keyword. Inside, each element is declared like a method with no parameters, and it can have a default value:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Arrays;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Author {
    String name();                       // required: no default value
    String date() default "unknown";     // optional
    int version() default 1;             // optional
    String[] reviewers() default {};     // optional array element
}

@Author(name = "Priya", version = 3, reviewers = {"Arjun", "Neha"})
class PaymentService {
}

@Author(name = "Rahul")
class LoginService {
}

class Main {

    static void printInfo(Class<?> cls) {
        Author a = cls.getAnnotation(Author.class);
        System.out.println(cls.getSimpleName() + " -> author: " + a.name()
                + ", date: " + a.date()
                + ", version: " + a.version()
                + ", reviewers: " + Arrays.toString(a.reviewers()));
    }

    public static void main(String[] args) {
        printInfo(PaymentService.class);
        printInfo(LoginService.class);
    }
}

Output:

PaymentService -> author: Priya, date: unknown, version: 3, reviewers: [Arjun, Neha]
LoginService -> author: Rahul, date: unknown, version: 1, reviewers: []

Let's go through it:

  • name() has no default, so it is required. Writing @Author() without a name would be a compile error.

  • Elements with a default are optional. LoginService did not set version, so it got 1.

  • Array elements use curly braces: reviewers = {"Arjun", "Neha"}. For a single item, the braces can be left out.

  • cls.getAnnotation(Author.class) reads the annotation at runtime. This is called reflection: a program looking at its own classes while it runs. We read element values by calling them like methods, such as a.name().

  • The two lines above @interface Author are meta-annotations (annotations on an annotation). They are explained in the next section.

Annotation elements are restricted. Their type can only be a primitive (int, boolean, ...), String, Class, an enum, another annotation, or a one-dimensional array of these. Wrapper types like Integer or any other class are not allowed. Values must be constants (such as literals, enum constants, or class literals like String.class), and null is never allowed, so default null is a compile error too.

Meta-Annotations: @Retention and @Target

When we create an annotation, we usually describe two things about it: how long it is kept, and where it may be used.

@Retention: how long is it kept?

RetentionPolicy

Kept until

Who can read it

Example

SOURCE

Compilation only; not stored in the .class file

The compiler and source-processing tools

@Override, @SuppressWarnings

CLASS (the default)

Stored in the .class file, but not loaded at runtime

Tools that read .class files

Rarely chosen on purpose

RUNTIME

Available while the program runs

Your code, using reflection

@Deprecated, @FunctionalInterface, JUnit's @Test

The default is CLASS, and this surprises many beginners. If you forget @Retention(RetentionPolicy.RUNTIME), reflection simply can't see your annotation:

import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;

@Retention(RetentionPolicy.RUNTIME)
@interface Visible {
}

@interface Invisible {     // no @Retention, so the default (CLASS) is used
}

@Visible
@Invisible
class Report {
}

class Main {
    public static void main(String[] args) {
        System.out.println("@Visible present?   " + Report.class.isAnnotationPresent(Visible.class));
        System.out.println("@Invisible present? " + Report.class.isAnnotationPresent(Invisible.class));
    }
}

Output:

@Visible present?   true
@Invisible present? false

Both annotations are written on Report, but only the RUNTIME one can be found while the program is running.

@Target: where can it be used?

@Target lists the kinds of declarations an annotation may be placed on, using values from the ElementType enum:

ElementType

Allowed on

TYPE

Classes, interfaces, enums, records (and annotation interfaces)

METHOD

Methods

FIELD

Fields (including enum constants)

PARAMETER

Method and constructor parameters

CONSTRUCTOR

Constructors

LOCAL_VARIABLE

Local variables

For example, with @Target(ElementType.METHOD), putting the annotation on a class is a compile error ("annotation interface not applicable to this kind of declaration"). To allow several places, use an array: @Target({ElementType.METHOD, ElementType.FIELD}). If you leave out @Target, the annotation can be used on almost any declaration.

Other meta-annotations

  • @Documented: the annotation appears in the Javadoc documentation of the code that uses it.

  • @Inherited: if a class has this annotation, its subclasses are treated as having it too. It only works for annotations on classes.

  • @Repeatable (Java 8): allows the same annotation to be written more than once on the same element, like @Schedule(day = "Monday") and @Schedule(day = "Thursday") on one class.

A Complete Example: A Mini Test Runner

How does a testing tool like JUnit know which methods are tests? You mark them with @Test, and the tool uses reflection to find and run them. Let's build a tiny version ourselves to see that there is no magic involved:

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.TreeMap;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Test {
    boolean enabled() default true;
}

class CalculatorTests {

    @Test
    static void additionWorks() {
        check(2 + 3 == 5);
    }

    @Test
    static void integerDivisionWorks() {
        check(10 / 3 == 3);
    }

    @Test
    static void multiplicationIsWrong() {
        check(2 * 3 == 5);          // deliberately wrong
    }

    @Test(enabled = false)
    static void slowNetworkTest() {
        check(false);
    }

    static void check(boolean condition) {   // no @Test: the runner ignores it
        if (!condition) {
            throw new AssertionError("check failed");
        }
    }
}

class Main {
    public static void main(String[] args) throws Exception {

        // getDeclaredMethods() returns methods in no fixed order,
        // so we sort them by name using a TreeMap
        TreeMap<String, Method> tests = new TreeMap<>();
        for (Method m : CalculatorTests.class.getDeclaredMethods()) {
            if (m.isAnnotationPresent(Test.class)) {
                tests.put(m.getName(), m);
            }
        }

        int passed = 0, failed = 0, skipped = 0;

        for (Method m : tests.values()) {
            Test test = m.getAnnotation(Test.class);

            if (!test.enabled()) {
                System.out.println("SKIP  " + m.getName());
                skipped++;
                continue;
            }

            try {
                m.invoke(null);                 // null: the method is static
                System.out.println("PASS  " + m.getName());
                passed++;
            } catch (InvocationTargetException e) {
                System.out.println("FAIL  " + m.getName() + " (" + e.getCause().getMessage() + ")");
                failed++;
            }
        }

        System.out.println(passed + " passed, " + failed + " failed, " + skipped + " skipped");
    }
}

Output:

PASS  additionWorks
PASS  integerDivisionWorks
FAIL  multiplicationIsWrong (check failed)
SKIP  slowNetworkTest
2 passed, 1 failed, 1 skipped

Here is what happens step by step:

  1. getDeclaredMethods() gives us all methods of CalculatorTests, including check().

  2. isAnnotationPresent(Test.class) keeps only the methods marked @Test. This works only because @Test has RUNTIME retention.

  3. The methods go into a TreeMap so they run in alphabetical order. Java does not guarantee any order for getDeclaredMethods().

  4. getAnnotation(Test.class).enabled() reads the element value, and disabled tests are skipped.

  5. m.invoke(null) calls the method (null because it is static). If the method throws an exception, invoke() wraps it in an InvocationTargetException, and getCause() gives us the original AssertionError.

Notice that @Test did nothing on its own. All of the behaviour came from the code in main() that reads the annotation. This is the most important idea of this chapter.

Annotations in Real Projects

You will see annotations constantly when you use Java frameworks. Some common ones:

Annotation

From

Purpose

@Test

JUnit

Marks a method as a unit test

@RestController, @GetMapping

Spring

Turn a class into a web API and map URLs to methods

@Autowired

Spring

Ask Spring to supply (inject) an object automatically

@Entity, @Id

JPA / Hibernate

Map a class to a database table and a field to its primary key

@Getter, @Setter

Lombok

Generate getters and setters during compilation

These frameworks read annotations in two main ways. Spring, JUnit and Hibernate mostly use reflection at runtime, just like our test runner. Lombok instead uses an annotation processor, which runs inside the compiler and works with SOURCE-level annotations.

Annotation vs Comment vs Interface

Feature

Comment

Annotation

Interface

Read by

Humans only

Compiler, tools, and programs

Compiler and the type system

Can carry values?

Free text

Yes, typed elements

Only constant fields

Changes behaviour?

Never

Only if something reads it

Yes, defines methods a class must implement

Available at runtime?

No

Only with RUNTIME retention

Yes

Common Mistakes

  • Forgetting @Retention(RetentionPolicy.RUNTIME). The default is CLASS, so isAnnotationPresent() returns false and your annotation looks "ignored".

  • Expecting an annotation to do something by itself. A custom annotation has no effect until some code (or tool) reads it.

  • Using unsupported element types. Integer, List, or default null are not allowed in an annotation element.

  • Overusing @SuppressWarnings. Putting it on a whole class can hide real bugs. Fix the warning if you can, and suppress it as narrowly as possible if you can't.

  • Confusing @Deprecated with @deprecated. The annotation (capital D) is what the compiler checks; the Javadoc tag (small d) is documentation.

Interview Tips

  • What is an annotation? Metadata attached to code using @. It doesn't change the code directly, but the compiler, tools, or frameworks can read it and act on it.

  • Name some built-in annotations. @Override, @Deprecated, @SuppressWarnings, @FunctionalInterface, @SafeVarargs.

  • What are the retention policies? SOURCE (discarded after compilation), CLASS (in the .class file, not at runtime; the default), RUNTIME (readable using reflection).

  • What is a meta-annotation? An annotation used on other annotations: @Retention, @Target, @Documented, @Inherited, @Repeatable.

  • How do you create a custom annotation? With @interface. Elements are declared like methods without parameters and may have default values.

  • Is @Override mandatory? No, overriding works without it, but it is strongly recommended because the compiler then checks that you really are overriding something.

The Main Idea

Annotations are labels with optional data that you attach to code. They don't do anything on their own; the compiler, tools, or your program (using reflection) read them and decide what to do.

Key points to remember:

  • Built-in annotations like @Override and @Deprecated let the compiler check your code and warn users.

  • Create your own with @interface; elements can have default values.

  • @Retention decides how long an annotation lives; use RUNTIME to read it with reflection.

  • @Target decides where an annotation may be used.

  • Frameworks like JUnit and Spring are built on annotations plus reflection.