Java反射之详细概述
一、反射的相关概念
反射概念:
框架:半成品软件。可以在框架的基础上进行软件开发,简化编码。
反射:将类的各个组成部分(成员变量/构造方法/成员方法)封装为对应的对象(Field),这就是反射机制。
好处:
1.可以在程序运行过程中,操作这些对象(Field,Constructor,Method)。
2.可以解耦,提高程序的可扩展性。
使用框架:了解反射
开发/研究框架:理解,灵活使用
二、反射_获取字节码Class对象的三种方式
获取字节码class的三种方式:
1.Class.forName(“全类名”):将字节码文件加载进内存,返回Class对象。
* 多用于配置文件,将类名定义在配置文件中。读取文件,加载类
2.类名.class:通过类名的属性class获取。
* 多用于参数的传递
3.对象.getClass():getClass()方法在Object类中定义着。
* 多用于对象的获取字节码的方式
结论:
同一个字节码文件(*.class)在一次程序运行过程中,只会被加载一次,不论通过哪一种方式获取的Class对象都是同一个。
代码:
public class ReflectDemo1 {
/**
获取Class对象的方式:
1. Class.forName("全类名"):将字节码文件加载进内存,返回Class对象
2. 类名.class:通过类名的属性class获取
3. 对象.getClass():getClass()方法在Object类中定义着。
*/
public static void main(String[] args) throws Exception {
//1.Class.forName("全类名")
Class cls1 = Class.forName("cn.itcast.domain.Person");
System.out.println(cls1);
//2.类名.class
Class cls2 = Person.class;
System.out.println(cls2);
//3.对象.getClass()
Person p = new Person();
Class cls3 = p.getClass();
System.out.println(cls3);
//== 比较三个对象
System.out.println(cls1 == cls2);//true
System.out.println(cls1 == cls3);//true
Class c = Student.class;
System.out.println(c == cls1);
}
}
补充:
三、反射_Class对象功能概述【应用】
Class对象的获取功能:
1. 获取成员变量们:
- Field[] getFields():获取所有public修饰的成员变量
- Field getField(String name):获取指定名称的 public修饰的成员变量
- Field[] getDeclaredFields():获取所有的成员变量,不考虑修饰符
- Field getDeclaredField(String name)
2. 获取构造方法们:
- Constructor<?>[] getConstructors()
- Constructor getConstructor(类<?>… parameterTypes)
- Constructor getDeclaredConstructor(类<?>… parameterTypes)
- Constructor<?>[] getDeclaredConstructors()
3. 获取成员方法们:
- Method[] getMethods()
- Method getMethod(String name, 类<?>… parameterTypes)
- Method[] getDeclaredMethods()
- Method getDeclaredMethod(String name, 类<?>… parameterTypes)
4. 获取全类名:
- String getName()
5.获取简单类名:
- String getSimpleName()
四、反射_Class对象功能_获取Field【应用】
常用API:
-
获取所有成员变量,不考虑修饰符
Field[] getDeclaredFields() -
根据名字获取成员变量,不考虑修饰符
Field getDeclaredField(String name) -
为成员变量设置值
void set(Object obj, Object value) -
获取成员变量的值
Object get(Object obj) -
访问private修饰的成员变量/构造方法/成员方法,true表示暴力反射
void setAccessible(boolean flag)
获取Field成员变量:
1.设置值
- p.setName(“张三”);
- void set(Object obj, Object value)
2.获取值
- String name = p.getName();
- get(Object obj)
3.忽略访问权限修饰符的安全检查,只要是private成员(Field/Constructor/Method)都这个方法
- setAccessible(true):暴力反射
代码:
public class ReflectDemo2 {
/**
Class对象功能:
* 获取功能:
1. 获取成员变量们
* Field[] getFields()
* Field getField(String name)
* Field[] getDeclaredFields()
* Field getDeclaredField(String name)
2. 获取构造方法们
* Constructor<?>[] getConstructors()
* Constructor<T> getConstructor(类<?>... parameterTypes)
* Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
* Constructor<?>[] getDeclaredConstructors()
3. 获取成员方法们:
* Method[] getMethods()
* Method getMethod(String name, 类<?>... parameterTypes)
* Method[] getDeclaredMethods()
* Method getDeclaredMethod(String name, 类<?>... parameterTypes)
4. 获取类名
* String getName()
*/
public static void main(String[] args) throws Exception {
//0.获取Person的Class对象
Class personClass = Person.class;
/*
1. 获取成员变量们
* Field[] getFields()
* Field getField(String name)
* Field[] getDeclaredFields()
* Field getDeclaredField(String name)
*/
//1.Field[] getFields()获取所有public修饰的成员变量
Field[] fields = personClass.getFields();
for (Field field : fields) {
System.out.println(field);
}
System.out.println("------------");
//2.Field getField(String name)
Field a = personClass.getField("a");
//获取成员变量a 的值
Person p = new Person();
Object value = a.get(p);
System.out.println(value);
//设置a的值
a.set(p,"张三");
System.out.println(p);
System.out.println("===================");
//Field[] getDeclaredFields():获取所有的成员变量,不考虑修饰符
Field[] declaredFields = personClass.getDeclaredFields();
for (Field declaredField : declaredFields) {
System.out.println(declaredField);
}
//Field getDeclaredField(String name)
Field d = personClass.getDeclaredField("d");
//忽略访问权限修饰符的安全检查
d.setAccessible(true);//暴力反射
Object value2 = d.get(p);
System.out.println(value2);
}
}
五、反射_Class对象功能_获取Constructor
常用API:
1.获取所有public修饰的构造方法
- Constructor[] getConstructors()
2.根据参数获取public修饰的构造方法
- Constructor getConstructor(Class<?>… parameterTypes)
3.使用构造方法创建对象
- T newInstance(Object… initargs)
4.获取Constructor构造方法
- 创建对象:
- T newInstance(Object… initargs)
(如果使用空参数构造方法创建对象,操作可以简化:Class对象的newInstance方法。)
代码:
public class ReflectDemo3 {
/**
Class对象功能:
* 获取功能:
1. 获取成员变量们
* Field[] getFields()
* Field getField(String name)
* Field[] getDeclaredFields()
* Field getDeclaredField(String name)
2. 获取构造方法们
* Constructor<?>[] getConstructors()
* Constructor<T> getConstructor(类<?>... parameterTypes)
* Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
* Constructor<?>[] getDeclaredConstructors()
3. 获取成员方法们:
* Method[] getMethods()
* Method getMethod(String name, 类<?>... parameterTypes)
* Method[] getDeclaredMethods()
* Method getDeclaredMethod(String name, 类<?>... parameterTypes)
4. 获取类名
* String getName()
*/
public static void main(String[] args) throws Exception {
//0.获取Person的Class对象
Class personClass = Person.class;
/*
2. 获取构造方法们
* Constructor<?>[] getConstructors()
* Constructor<T> getConstructor(类<?>... parameterTypes)
* Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
* Constructor<?>[] getDeclaredConstructors()
*/
//Constructor<T> getConstructor(类<?>... parameterTypes)
Constructor constructor = personClass.getConstructor(String.class, int.class);
System.out.println(constructor);
//创建对象
Object person = constructor.newInstance("张三", 23);
System.out.println(person);
System.out.println("----------");
Constructor constructor1 = personClass.getConstructor();
System.out.println(constructor1);
//创建对象
Object person1 = constructor1.newInstance();
System.out.println(person1);
Object o = personClass.newInstance();
System.out.println(o);
//constructor1.setAccessible(true);
}
}
五、反射_Class对象功能_获取Method【应用】
常用API:
1.获取所有public修饰的方法
- Method[] getMethods()
2.根据方法名和参数列表获取public修饰的方法
- Method getMethod(String name, Class<?>… parameterTypes)
3.获取方法名
- String getName()
4.执行方法
- Object invoke(Object obj, Object… args)
5.获取Method成员方法
5.1 执行方法:
- Object invoke(Object obj, Object… args)
5.2获取方法名称:
- String getName:获取方法名
代码:
public class ReflectDemo4 {
/**
Class对象功能:
* 获取功能:
1. 获取成员变量们
* Field[] getFields()
* Field getField(String name)
* Field[] getDeclaredFields()
* Field getDeclaredField(String name)
2. 获取构造方法们
* Constructor<?>[] getConstructors()
* Constructor<T> getConstructor(类<?>... parameterTypes)
* Constructor<T> getDeclaredConstructor(类<?>... parameterTypes)
* Constructor<?>[] getDeclaredConstructors()
3. 获取成员方法们:
* Method[] getMethods()
* Method getMethod(String name, 类<?>... parameterTypes)
* Method[] getDeclaredMethods()
* Method getDeclaredMethod(String name, 类<?>... parameterTypes)
4. 获取类名
* String getName()
*/
public static void main(String[] args) throws Exception {
//0.获取Person的Class对象
Class personClass = Person.class;
/*
3. 获取成员方法们:
* Method[] getMethods()
* Method getMethod(String name, 类<?>... parameterTypes)
* Method[] getDeclaredMethods()
* Method getDeclaredMethod(String name, 类<?>... parameterTypes)
*/
//获取指定名称的方法
Method eat_method = personClass.getMethod("eat");
Person p = new Person();
//执行方法
eat_method.invoke(p);
Method eat_method2 = personClass.getMethod("eat", String.class);
//执行方法
eat_method2.invoke(p,"饭");
System.out.println("-----------------");
//获取所有public修饰的方法
Method[] methods = personClass.getMethods();
for (Method method : methods) {
System.out.println(method);
String name = method.getName();
System.out.println(name);
//method.setAccessible(true);
}
//获取类名
String className = personClass.getName();
System.out.println(className);//cn.itcast.domain.Person
}
}
补充:
如何用反射获取main方法:
public class Student {
public static void main(String[] args) {
System.out.println("我这main方法");
}
}
public class ReflectDemo01 {
public static void main(String[] args) throws Exception {
Class studentClass = Student.class;
//System.out.println(studentClass.getName());//com.itheima.reflect.subject02.Student
//System.out.println(studentClass.getSimpleName());//Student
Method method = studentClass.getMethod("main", String[].class);
System.out.println(method);
System.out.println(method.getName());
//method.invoke(null,new String[]{"a","b","c"});//wrong number of arguments
//main方法的参数虽然是String[]数组,但需要将其封装到一个Object[]数组中
//因为反射时,自动获取Object[]数组中的第1个参数做为实际值。
method.invoke(null,new Object[]{new String[]{"a","b","c"}});
}
}
六、反射_案例【应用】
代码:
pro.properties文件
className=cn.itcast.domain.Student
methodName=sleep
/**
* 框架类
*/
public class ReflectTest {
public static void main(String[] args) throws Exception {
//可以创建任意类的对象,可以执行任意方法
/*
前提:不能改变该类的任何代码。可以创建任意类的对象,可以执行任意方法
*/
/* Person p = new Person();
p.eat();*/
/*
Student stu = new Student();
stu.sleep();*/
//1.加载配置文件
//1.1创建Properties对象
Properties pro = new Properties();
//1.2加载配置文件,转换为一个集合
//1.2.1获取class目录下的配置文件
ClassLoader classLoader = ReflectTest.class.getClassLoader();
InputStream is = classLoader.getResourceAsStream("pro.properties");
pro.load(is);
//2.获取配置文件中定义的数据
String className = pro.getProperty("className");
String methodName = pro.getProperty("methodName");
//3.加载该类进内存
Class cls = Class.forName(className);
//4.创建对象
Object obj = cls.newInstance();
//5.获取方法对象
Method method = cls.getMethod(methodName);
//6.执行方法
method.invoke(obj);
}
}
补充:
关于类加载器加载路径的写法:
-
pro.properties文件放在src目录下(推荐):
InputStream is = ReflectDemo01.class
.getClassLoader().getResourceAsStream(“pro.properties”); -
pro.properties文件放在com.itheima.test目录下:
InputStream is = ReflectDemo01.class
.getClassLoader().getResourceAsStream(“com/itheima/test/pro.properties”);
关于配置文件的扩展名
- pro.properties(推荐)