← Back to Core Java Course | Chapter 13: Advanced Topics & Reference | Lesson 6 of 10

Java Annotations

Built-in Standard Annotations

Built-in annotations like @Override and @FunctionalInterface don't change runtime behavior directly — they let the compiler catch mistakes, like a mistyped method name that fails to actually override anything.

Example: Built-in Standard Annotations

java
class Animal {
	void sound() { System.out.println("Some sound"); }
}
class Dog extends Animal {
	@Override // compiler catches a mistyped override
	void sound() { System.out.println("Bark"); }
}
public class Main {
	public static void main(String[] args) {
		new Dog().sound();
	}
}

Deprecation Annotations

@Deprecated marks a method or class as discouraged for future use, triggering a compiler warning at call sites and signaling to other developers that a newer alternative exists.

Example: Deprecation Annotations

java
class Util {
	@Deprecated
	static void oldMethod() {
		System.out.println("Old behavior");
	}
}
public class Main {
	public static void main(String[] args) {
		Util.oldMethod(); // triggers a compiler warning
	}
}

Defining Custom Annotations

A custom annotation is defined with @interface, optionally including elements (which look like methods) that callers fill in as named or positional arguments when applying the annotation.

Example: Defining Custom Annotations

java
@interface Author {
	String name();
}
@Author(name = "Alice")
class Report {
}
public class Main {
	public static void main(String[] args) {
		System.out.println("Custom annotation applied");
	}
}

Annotation Retention and Target

@Retention controls whether an annotation survives to runtime or is discarded after compilation, and @Target restricts which kinds of declarations (methods, fields, classes) it can legally be applied to.

Example: Annotation Retention and Target

java
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@interface Loggable {
}
public class Main {
	@Loggable
	static void run() {
		System.out.println("Running");
	}
	public static void main(String[] args) {
		run();
	}
}

Reading Annotations at Runtime

Reading annotations at runtime requires Java's reflection API — calling getAnnotation() on a Class, Method, or Field object to inspect what was applied, which is how frameworks like Spring implement much of their configuration.

Example: Reading Annotations at Runtime

java
import java.lang.annotation.*;
import java.lang.reflect.Method;
@Retention(RetentionPolicy.RUNTIME)
@interface Loggable {
}
public class Main {
	@Loggable
	static void run() {}
	public static void main(String[] args) throws NoSuchMethodException {
		Method m = Main.class.getDeclaredMethod("run");
		System.out.println(m.isAnnotationPresent(Loggable.class));
	}
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.