Annotation

An annotation is metadata attached to a class, method, field, or parameter with the @ symbol. It doesn't execute — it is read by the compiler, tools, or runtime frameworks (Spring, JPA, Jackson, JUnit) to change behaviour.

Built-in annotations

@Override           // must override a method from the parent
public String toString() { return "..."; }

@Deprecated         // marks the method for removal
public void oldMethod() {}

@SuppressWarnings("unchecked")
List<String> list = (List<String>) rawList;

@FunctionalInterface
public interface Transformer<T> { T apply(T input); }

Framework annotations

// Spring:
@RestController
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public User get(@PathVariable long id) { ... }
}

// JPA:
@Entity
@Table(name = "users")
public class User {
    @Id @GeneratedValue
    private Long id;
}

// JUnit 5:
@Test
void testAddition() { ... }

Define your own

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Audited {
    String value() default "";
}

@Audited("payment-processing")
public void processPayment() { ... }

Retention policies

  • SOURCE — discarded at compile time (e.g. @Override).
  • CLASS — stored in the .class file but not available via reflection at runtime.
  • RUNTIME — available via reflection; frameworks read them at runtime.