自定义注解
Jihongchang(讨论 | 贡献)2024年7月10日 (三) 09:05的版本
简单的 Annotaion
Test.java
/**
* 定义一个简单的 Annotation 类型
*/
public @interface Test {
}
定义了该 Annotation 之后,就可以在程序的任何地方使用该 Annotation, MyClass.java
// 使用 @Test 修饰类定义
@Test
public class MyClass {
}
默认情况下,Annotation 可用于修饰任何程序元素,包括类、接口、方法等, MyClass1.java
public class MyClass1 {
// 使用 @Test Annotation 修饰方法
@Test
public void info() {
}
}
带成员变量的 Annotation
MyTag.java
public @interface MyTag {
// 定义了两个成员变量的 Annotation
String name();
int age();
}
Test1.java
public class Test1 {
// 使用带成员变量的 Annotation 时,需要为成员变量赋值
@MyTag(name="xx", age=6)
public void info() {
}
}
成员变量有默认值的 Annotation
public @interface MyTag1 {
// 定义了两个成员变量的 Annotation
// 使用 default 为两个成员变量指定初始值
String name() default "yeehu";
int age() default 32;
}
如果为 Annotation 的成员变量指定了默认值,使用该 Annotation 时则可以不为这些成员变量指定值,而是直接使用默认值。
public class Test2 {
// 使用带成员变量的 Annotation
// 因为它的成员变量有默认值,所以可以不为它的成员变量指定值
@MyTag1
public void info() {
}
}
当使用 Annotation 修饰了类、方法、Field等成员之后,这些 Annotation 不会自己生效,必须提供相应的工具来提取并处理 Annotation 信息。
Java 使用 java.lang.annotation.Annotation 接口来代表程序元素前面的注释,该接口是所有 Annotation 类型的父接口。