java.lang.reflect 包主要包含一些实现反射功能的工具类,另外也提供了对读取运行
时注解的支持。java.lang.reflect 包下的 AnnotatedElement 接口代表程序中可以接受注解
的程序元素,该接口有如下几个实现类。
- Class 类
- Constructor :构造方法定义
- Field:类的成员变量定义
- Method:类的方法定义
- Package:类的包定义
java.lang.reflect.AnnotatedElement 接口是所有程序的父接口,程序通过反射获得
某个类的 AnnotatedElement 对象(如类、方法和成员变量),调用该对象的 3 个方法
就可以来访问注解信息。
1. getAnnotation()方法:用于返回该元素上存在的、指定类型的注解,如果该
类型的注解不存在,则返回 null。
2.getAnnotations() 方法:用来返回该程序元素上存在的所有注解。
3.isAnnotationPresent() 方法:用来判断该程序元素上是否包含指定类型的注解,
如果存在则返回 true,否则返回 false。
例如下面代码中,获取了MyAnnotion 类的 getObjectInfo() 方法的所有注解,并输出。
import java.lang.annotation.Annotation;
/**
* @author Darren
* @create Darren QQmailbox:395648542@qq.com Blog address:https://blog.csdn.net/weixin_44129498
* @create 2019/8/20
* @create 6:47
*/
public class MyAnnotation {
// 获取 MyAnnotation 类的 getObjectInfo()方法的所有注解
Annotation[] arr = Class.forName("MyAnnotation").getMethod("getObjectInfo").getAnnotations();
//遍历所有注解
for(Annotation an:arr){
System.out.println(an);
}
}
需要注意的是,这里得到的注解,都是被定义为运行时的注解,即都是用@Retention
(RetentionPolicy.RUNTIME)修饰的注解。否则,通过反射得不到这个注解信息。因为
当一个注解类型被定义为运行时注解,该注解在运行时才是可见的。当 Class 文件被装载时,
保存在 class 文件中的注解才会被 Java 虚拟机所读取。
有时候需要获取某个注解里的元数据,则可以将注解强制类型转换成所需的注解类型,
然后通过注解对象的抽象方法来访问这些元数据。