In Java, annotations are metadata that you can attach to code elements (classes, methods, variables, parameters, packages, etc.) to give additional information to the compiler, tools, or runtime.
They do not directly affect the execution of code but can influence it through processing (for example, frameworks like Spring or JUnit use annotations heavily).
1. Basic Syntax
Annotations start with @
and can have optional parameters.
public class MyClass {
@Override
public String toString() {
return "Example";
}
@Deprecated
public void oldMethod() {
System.out.println("This method is deprecated");
}
}
2. Types of Annotations
a. Built-in Annotations
Java provides several standard annotations:
@Override
– checks if a method actually overrides a method in the superclass.@Deprecated
– marks a method/class as outdated.@SuppressWarnings
– tells the compiler to ignore specific warnings.
Example:
@SuppressWarnings("unchecked")
public void doSomething() { }
b. Meta-Annotations
These are annotations used to create other annotations:
@Target
– where the annotation can be applied (class, method, field, etc.).@Retention
– how long the annotation is kept (SOURCE
,CLASS
, orRUNTIME
).@Documented
– include the annotation in Javadoc.@Inherited
– allows subclasses to inherit the annotation.
3. Creating a Custom Annotation
Example:
import java.lang.annotation.*;
@Retention(RetentionPolicy.RUNTIME) // Available at runtime
@Target(ElementType.METHOD) // Can be applied to methods
public @interface MyAnnotation {
String value();
int priority() default 1; // default value
}
Using it:
public class Test {
@MyAnnotation(value = "Hello", priority = 2)
public void sayHello() {
System.out.println("Hello World!");
}
}
4. Processing Annotations
At runtime, you can read annotations via Reflection:
import java.lang.reflect.Method;
public class AnnotationReader {
public static void main(String[] args) throws Exception {
Method method = Test.class.getMethod("sayHello");
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
if (annotation != null) {
System.out.println("Value: " + annotation.value());
System.out.println("Priority: " + annotation.priority());
}
}
}
✅ Summary Table
Feature | Purpose |
---|---|
@Override | Ensures method overrides parent method |
@Deprecated | Marks code as outdated |
@SuppressWarnings | Hides compiler warnings |
@Target | Restricts where annotation can be used |
@Retention | Defines annotation’s lifetime |
Custom Annotation | Define your own metadata |