Java Custom Annotations Guide
To customize annotations, first use the “@interface” keyword to define an annotation, and then simply use the annotation where it is needed.
The example code is shown below:
// 自定义注解
public @interface MyAnnotation {
String value();
}
// 使用注解
@MyAnnotation(value = "Hello")
public class MyClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
// 获取注解的值
MyAnnotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value()); // 输出:Hello
}
}
In the example above, a custom annotation named MyAnnotation is first defined. It is then used on the MyClass class with the value attribute set to “Hello”. Using reflection in the main method, the value of the MyAnnotation on the MyClass class is obtained and printed.