Java
Annotations
Master Java annotations for metadata and framework integration.
By TechCoder TeamLast updated: 2026-06-02
In a Nutshell
Master Java annotations for metadata and framework integration. This hands-on tutorial focuses on practical implementation of annotations concepts.
Annotations
Annotations provide metadata about the program.
Built-in Annotations
@Override
Indicates a method overrides a superclass method.
@Override
public String toString() {
return "MyClass";
}
@Deprecated
Marks code as outdated.
@Deprecated
public void oldMethod() {
// Don't use this!
}
@SuppressWarnings
Suppresses compiler warnings.
@SuppressWarnings("unchecked")
List list = new ArrayList();
Meta-Annotations
Used to create custom annotations.
@Retention
How long the annotation is retained.
@Retention(RetentionPolicy.RUNTIME) // Available at runtime
@Retention(RetentionPolicy.SOURCE) // Discarded by compiler
@Retention(RetentionPolicy.CLASS) // In .class file, not at runtime
@Target
Where the annotation can be applied.
@Target(ElementType.METHOD) // Only on methods
@Target(ElementType.TYPE) // On classes/interfaces
@Target(ElementType.FIELD) // On fields
Custom Annotations
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Test {
int priority() default 1;
String author();
}
// Usage
@Test(priority = 2, author = "Alice")
public void myTest() {
// Test code
}
Processing Annotations with Reflection
Method[] methods = MyClass.class.getDeclaredMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(Test.class)) {
Test test = method.getAnnotation(Test.class);
System.out.println("Priority: " + test.priority());
System.out.println("Author: " + test.author());
}
}
AI Mentor
Confused about "Java annotations and custom annotation creation"? Ask our AI mentor for a simplified explanation.
Quiz
Quiz
Question 1 of 3What does @Override do?
Forces method override
Indicates method overrides superclass
Creates new method