What is the method for creating custom annotations in J…
In Java, the method for creating custom annotations is as follows:
- Definition
public @interface MyAnnotation {
// 注解元素
}
- Annotations can be applied to elements such as primitive data types, Strings, Classes, enum types, annotation types, or arrays of them.
public @interface MyAnnotation {
String value(); // 定义一个字符串类型的注解元素
int count() default 1; // 定义一个整数类型的注解元素,并设置默认值为1
}
- When using annotations, you can specify corresponding values for the annotation elements.
@MyAnnotation(value = "Hello", count = 3)
public class MyClass {
// 类的内容
}
- Retrieve annotation information through reflection where annotations are needed.
MyAnnotation annotation = MyClass.class.getAnnotation(MyAnnotation.class);
String value = annotation.value(); // 获取注解元素的值
int count = annotation.count();
- In places where annotations are needed, the use of default values for elements can simplify the use of annotations.
@MyAnnotation("Hello")
public class MyClass {
// 类的内容
}