请问自定义注解不添加Retention注解的话,它的默认生民周期是多少?
先说答案,默认生命周期是Class,也就是说,不加@Retention的话,这个注解只存在class中。看我的测试:
源码:
package csdn20220823;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;
/**
* @Description
* @Author wangFei
* @Date 2022/8/23 17:36
* @Version 1.0
**/
public class Test {
@wf
private String name;
public static void main(String[] args) throws InterruptedException {
System.out.println("Test class");
Thread.sleep(100000);
}
}
class Test2 {
public static void main(String[] args) throws ClassNotFoundException {
Class test = Class.forName("csdn20220823.Test");
Field[] interfaces = test.getDeclaredFields();
for (Field c : interfaces) {
System.out.println(c.isAnnotationPresent(wf.class));
}
}
}
/**
* @author wf
*/
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@interface wf {
String value() default "";
}
测试步骤:
加@Retention注解测试
1、先启动Test里面的main
2、再启动Test2里面的main
3、再去掉@Retention
4、启动Test里面的main
5、再启动Test2里面的main
结果是false。说明wf注解只存在字节码里面