在自定义注解时,如何使用@Retention元注解?请给出具体示例。
/**
* 自定义注解的 Retention 使用示例
* 在Java中,@Retention元注解用于指定注解的生命周期,即注解在什么阶段有效。它有以下三种取值:
* 1. RetentionPolicy.SOURCE:注解仅存在于源码中,编译时会被丢弃。
* 2. RetentionPolicy.CLASS:注解在编译时会被保留,但运行时不可见(默认值)。
* 3. RetentionPolicy.RUNTIME:注解在运行时也会保留,可以通过反射机制读取。
*/
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
// 定义一个运行时保留的自定义注解
@Retention(RetentionPolicy.RUNTIME)
public @interface MyCustomAnnotation {
String value() default "默认值";
int count() default 0;
}
// 使用自定义注解
public class AnnotationExample {
@MyCustomAnnotation(value = "测试注解", count = 5)
public void testMethod() {
System.out.println("这是一个使用了自定义注解的方法");
}
public static void main(String[] args) {
try {
// 通过反射获取注解信息
MyCustomAnnotation annotation = AnnotationExample.class
.getMethod("testMethod")
.getAnnotation(MyCustomAnnotation.class);
System.out.println("value: " + annotation.value());
System.out.println("count: " + annotation.count());
} catch (NoSuchMethodException e) {
e.printStackTrace();
}
}
}
/**
* 示例解析:
* 1. 定义注解时,通过@Retention(RetentionPolicy.RUNTIME)指定该注解在运行时有效。
* 2. 注解中可以定义属性,如value和count,并可以设置默认值。
* 3. 在类或方法上使用该注解时,可以通过反射获取注解的具体值。
* 4. 如果不指定@Retention,默认是RetentionPolicy.CLASS。
*
* 实际应用场景:
* - 在框架开发中,常用于标记需要特殊处理的类或方法,比如Spring的@Controller。
* - 在测试框架中,如JUnit的@Test注解。
*/