Ability to add additional information to classes, methods, packages, etc.
import static java.lang.annotation.ElementType.TYPE;
import java.lang.annotation.Retention;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Target;
@Retention(RUNTIME)
@Target(TYPE)
public @interface TestAnnotation {
String testValue();
}
@Retention
Specifies the range in which annotation information is retained.
--SOURCE
Discarded by the compiler.
--CLASS
Recorded in class files by the compiler, but not read at run time. (Default)
--RUNTIME
Recorded in class files by the compiler and read at run time.
@Target
Specifies where annotations can be applied.
--TYPE
class, interface or enum declaration
--FIELD
field declaration
--METHOD
method declaration
--Declaration of argument of PARAMETER
method
--CONSTRUCTOR
Constructor declaration
--LOCAL_VARIABLE
Local variable declaration
--ʻANNOTATION_TYPE Annotation declaration --
PACKAGE Package Declaration --
TYPE_PARAMETERtype argument declaration --Where the
TYPE_USE type is used --
MODULE` module declaration
@interface
Define the annotation.
@TestAnnotation(testValue = "test value")
public class AnnotatedClass {
}
This time, we are annotating the class.
public class GetValue {
public static void main(String[] args) {
try {
Class<?> targetClass = Class.forName("AnnotatedClass");
var testAnnotation = (TestAnnotation) targetClass.getAnnotation(TestAnnotation.class);
System.out.println(testAnnotation.testValue());
} catch (Exception e) {
//Handling of exceptions
}
}
}
When executed, test value is output.
Recommended Posts