一、反射
什么是反射?
反射是一种可以在编译时获得解析类的能力。简单来说,通过反射可以直接创建对象、获得对象的属性、获得对象的方法
1、获得Class对象
// 反射的第一步:获取需要操作的对象的 Class
// 方式一:
Class pClass = new Task().getClass();
// 方式二:
Class pClass2 =Task.class;
// 方式三:
Class pClass3 =Class.forName("com.example.management.bean.Task");
System.out.println(pClass);
System.out.println(pClass2);
System.out.println(pClass3);
System.out.println(pClass==pClass2);
System.out.println(pClass==pClass3);
运行结果:
class com.example.management.bean.Task
class com.example.management.bean.Task
class com.example.management.bean.Task
true
true
注意:Class对象(反射对象)是和类一一对应的,一个类一定只有一个Class对象,不管通过什么方式获得的。Class对象是这个类加载到jvm内存中时创建的
2、通过Class对象,创建对应的类对象
Task task = (Task) pClass.newInstance();
注意:这种方式只能调用源类中的无参数构造方法
3、通过Class对象,获得源类的访问修饰符
// 获取源类的修饰符(是否是私有、公共、静态等)
Class pClass = new DoingService().getClass();
int modifiers = pClass.getModifiers();
System.out.println("这个类不是私有的"+ Modifier.isPrivate(modifiers));
System.out.println("这个类不是共有的"+ Modifier.isPublic(modifiers));
System.out.println("这个类不是私有的"+ Modifier.isStatic(modifiers));
运行结果
这个类不是私有的false
这个类不是共有的true
这个类不是私有的false
4、通过Class对象,获得源类的父类、接口、注解
Class pClass2 = new DoingController().getClass();
// 获取当前类父类的 Class对象
Class sClass = pClass2.getSuperclass();
System.out.println("父类的类型是:"+sClass);
// 获取当前类的所有接口的 Class对象
Class[] interfaces = pClass2.getInterfaces();
if (interfaces !=null){
for (Class anInterface : interfaces) {
System.out.println("实现接口类型为:"+anInterface.getName());
}
}
// 获取当前类的所有注解
Annotation[] annotations = pClass2.getAnnotations();
for (Annotation annotation : annotations) {
System.out.println("类的注解类型有:"+annotation.annotationType().getName());
}
运行结果:(没有实现接口所有没显示出来)
父类的类型是:class java.lang.Object
类的注解类型有:org.springframework.stereotype.Controller
类的注解类型有:org.springframework.web.bind.annotation.RequestMapping
5、获得源类中的各种属性
6、属性的各种操作
7、获得源类中的各种方法
8、通过反射操作数组