注解是不干扰原来的代码的执行的,起到一种标识作用,让第三方的注解工具来提
取注解,来完成所需的任务。
package two.zj; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Documented @Retention<span style="color:#ff0000;">(</span><span style="background-color: rgb(255, 0, 0);">RetentionPolicy.RUNTIME</span><span style="color:#ff0000;">)</span> @Target(ElementType.METHOD) public @interface TestZJ { public int id() default 1; public String name() default "nametest"; public String value() ; public abstract int [] intt(); public abstract TestEnum[] tenum(); }
package two; import two.zj.TestEnum; import two.zj.TestZJ; public class UserAnn { <span style="white-space:pre"> </span>/** <span style="white-space:pre"> </span> * @param user <span style="white-space:pre"> </span> * @return user <span style="white-space:pre"> </span> */ <span style="white-space:pre"> </span>@TestZJ(id=22,name="liyy", intt = { 0,1,2,3 }, value = "", tenum = {TestEnum.TEST1}) <span style="white-space:pre"> </span>public User getUser(User user) { <span style="white-space:pre"> </span>return user; <span style="white-space:pre"> </span>} }
package two;
import java.lang.reflect.Method;
import two.zj.TestZJ;
public class Testmain {
public static void main(String[] args) throws ClassNotFoundException {
// Class class1 = Class.forName("two.UserAnn");
Class class1 = UserAnn.class;
Method [] methods = class1.getDeclaredMethods();
for(Method method:methods){
TestZJ annotations = method.getAnnotation(TestZJ.class);
if(annotations !=null){
System.out.println(annotations.id());
}
}
}
}
当注解类TestZJ中的@Retention(RetentionPolicy.RUNTIME) 为source 或者class 时候 反射是获取不到注解类的,因为jdk用说明
public enum RetentionPolicy {
/**
* Annotations are to be discarded by the compiler.
*/
SOURCE,
/**
* Annotations are to be recorded in the class file by the compiler
* but need not be retained by the VM at run time. This is the default
* behavior.
*/
CLASS,
/**
* Annotations are to be recorded in the class file by the compiler and
* retained by the VM at run time, so they may be read reflectively.
*
* @see java.lang.reflect.AnnotatedElement
*/
RUNTIME
}
SOURCE在编译的c字节码中去掉注解,CLASS 字节码中有注解但是不加载到虚拟机,RUNTIME可以通过反射获取到注解信息,而注解框架也是采用的这种原理。