Retention元注解
1. Retetion简介
Retention:Java的元注解之一,用来解释注解的注解。这个注解用来修饰其他注解保留的生命周期(范围), 如果注释类型声明中没有保留注释,则保留策略默认为RetentionPolicy.CLASS 。
-
RetentionPolicy.SOURCE:仅存在源码中,不存在class文件。

-
RetentionPolicy.CLASS:这是默认的注解保留策略。注解存在于.class文件中,但是不能被JVM加载。

-
RetentionPolicy.RUNTIME:注解可以被JVM运行时访问到,通常可以结合反射来做一些事情。

2. 生命周期测试
-
RetentionPolicy.SOURCE,注解只保存在.java的源代码中,class字节码文件并不会存在。因此字节码文件 和 JVM运行时利用反射来加载获取到的注解个数都是0。
//SourceAnotation.java 注解文件 package annotation.Retention;import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.SOURCE) public @interface SourceAnotation {}//A1.java文件 package annotation.Retention;@SourceAnotation public class A1 {}//A2.java文件 package annotation.Retention;public class A2 { }@Test public void testSource() throws ClassNotFoundException {Class a1 = Class.forName("annotation.Retention.A1");Class a2 = Class.forName("annotation.Retention.A2");System.out.println(a1.getAnnotations().length);System.out.println(a2.getAnnotations().length); }
-
RetentionPolicy.CLASS:注解保留在java、class文件中,但是JVM运行时并不会将其加载。因此利用反射来获取注解数目都是0,但是字节码文件是不同的。
//ClassAnotation.java注解文件package annotation.Retention;import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.CLASS) public @interface ClassAnotation { }//B1.java文件 package annotation.Retention;@ClassAnotation public class B1 { }//B2.java文件 package annotation.Retention;public class B2 { }@Test public void testClass() throws ClassNotFoundException {Class b1 = Class.forName("annotation.Retention.B1");Class b2 = Class.forName("annotation.Retention.B2");System.out.println(b1.getAnnotations().length);System.out.println(b2.getAnnotations().length); }
-
RetentionPolicy.RUNTIME:注解保留在java、class文件中,并且JVM运行时能通过反射加载到这个注解。
//RunTimeAnotation.java注解文件 package annotation.Retention;import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy;@Retention(RetentionPolicy.RUNTIME) public @interface RunTimeAnotation { }//C1.java package annotation.Retention;@RunTimeAnotation public class C1 { }//C2.java package annotation.Retention; public class C2 { }@Test public void testRunTime() throws ClassNotFoundException {Class c1 = Class.forName("annotation.Retention.C1");Class c2 = Class.forName("annotation.Retention.C2");System.out.println(c1.getAnnotations().length);System.out.println(c2.getAnnotations().length); }
本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!
