Java Annotations
In this page:
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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
}
}
Login to try C/C++/Java/PHP code in the editor
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
@interface Author {
String name();
}
@Author(name = "Alice")
class Report {
}
public class Main {
public static void main(String[] args) {
System.out.println("Custom annotation applied");
}
}
Login to try C/C++/Java/PHP code in the editor
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
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();
}
}
Login to try C/C++/Java/PHP code in the editor
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
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 try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 10 topics to unlock
0/10 topics done
Complete these topics first: