Annotations and Reflection
Custom Annotation
A runtime annotation stores small metadata that reflection can read later.
Custom Annotation
CustomAnnotation.java
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface Lesson {
String name();
int level();
}
@Lesson(name = "reflection", level = 2)
class AnnotatedExample {
}
public class CustomAnnotation {
public static void main(String[] args) {
int bonus = ;
Lesson lesson = AnnotatedExample.class.getAnnotation(Lesson.class);
int adjustedLevel = lesson.level() + bonus;
System.out.println("name=" + lesson.name());
System.out.println("level=" + adjustedLevel);
}
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface Lesson {
String name();
int level();
}
@Lesson(name = "reflection", level = 2)
class AnnotatedExample {
}
public class CustomAnnotation {
public static void main(String[] args) {
int bonus = ;
Lesson lesson = AnnotatedExample.class.getAnnotation(Lesson.class);
int adjustedLevel = lesson.level() + bonus;
System.out.println("name=" + lesson.name());
System.out.println("level=" + adjustedLevel);
}
}
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
@Retention(RetentionPolicy.RUNTIME)
@interface Lesson {
String name();
int level();
}
@Lesson(name = "reflection", level = 2)
class AnnotatedExample {
}
public class CustomAnnotation {
public static void main(String[] args) {
int bonus = ;
Lesson lesson = AnnotatedExample.class.getAnnotation(Lesson.class);
int adjustedLevel = lesson.level() + bonus;
System.out.println("name=" + lesson.name());
System.out.println("level=" + adjustedLevel);
}
}
annotation type
An annotation type declares the metadata fields that can be attached to a program element.
runtime retention
Runtime retention keeps annotation metadata available to reflection while the program runs.