thecodex.expert · The Codex Family of Knowledge
Java

Annotations

@Override adds zero bytes to the compiled program’s actual logic — it exists purely so the compiler can catch a typo in a method name meant to override a superclass method.

Java 21 LTS Metadata, not code Last verified:
Canonical Definition

An annotation, written with @Name, attaches metadata to a declaration without being executable code itself. Built-in annotations like @Override (verifies a method actually overrides a superclass method, catching a misspelled method name at compile time) and @Deprecated (marks an API as discouraged, triggering a compiler warning at every use) are checked by the compiler. Custom annotations are typically read later, either by annotation processors at build time or via reflection at runtime, and frameworks like Spring rely heavily on this mechanism to wire up behavior declaratively.

Built-in annotations: @Override, @Deprecated, @SuppressWarnings

@Override catches a real, common mistake: misspelling a method name intended to override a superclass method silently creates a brand-new, unrelated method instead — without @Override, the compiler has no way to warn you.

JavaOverriding.java
class Animal {
    public void makeSound() { System.out.println("..."); }
}

class Dog extends Animal {
    @Override
    public void makeSund() {   // TYPO — but without @Override, this compiles silently
        System.out.println("Woof");
    }
    // WITH @Override present here: COMPILE ERROR, method does not override anything
    // catching the typo immediately instead of a silent, confusing runtime bug
}

Writing a custom annotation

@Retention controls whether the annotation survives to runtime (RUNTIME) or is discarded after compilation (SOURCE, CLASS); @Target restricts which kinds of declarations it can be applied to.

JavaTodo.java
import java.lang.annotation.*;

@Retention(RetentionPolicy.RUNTIME)   // keep it available for reflection at runtime
@Target(ElementType.METHOD)             // only valid on methods
public @interface Todo {
    String value();   // a required "parameter" for the annotation
}

class Report {
    @Todo("Add input validation")
    public void generate() { /* ... */ }
}

Reading annotations with reflection

This is how frameworks discover and act on annotations at runtime — Spring's @Autowired, JUnit's @Test, and countless others work by scanning classes reflectively for their own annotations, then acting on what they find.

JavaReadAnnotation.java
Method method = Report.class.getMethod("generate");
if (method.isAnnotationPresent(Todo.class)) {
    Todo todo = method.getAnnotation(Todo.class);
    System.out.println("TODO: " + todo.value());
}

Sources

1
Oracle. The Java Tutorials, "Annotations," docs.oracle.com/javase/tutorial/java/annotations/index.html.