30_Java中的反射
Java中的反射
一、类加载器
1、类加载:
类加载的描述
当程序要使用某个类时,如果该类还未被加载到内存中,则系统会通过类的加载,类的连接,类的初始化这三个步骤来对类进行初始化。如果不出现意外情况,JVM将会连续完成这三个步骤,所以有时也把这三个步骤统称为类加载或者类初始化
类的加载
就是指将class文件读入内存,并为之创建一个 java.lang.Class 对象
任何类被使用时,系统都会为之建立一个 java.lang.Class 对象
类的连接
验证阶段:用于检验被加载的类是否有正确的内部结构,并和其他类协调一致
准备阶段:负责为类的类变量分配内存,并设置默认初始化值
解析阶段:将类的二进制数据中的符号引用替换为直接引用
类的初始化
在该阶段,主要就是对类变量进行初始化
类的初始化步骤
假如类还未被加载和连接,则程序先加载并连接该类
假如该类的直接父类还未被初始化,则先初始化其直接父类
假如类中有初始化语句,则系统依次执行这些初始化语句
注意:在执行第2个步骤的时候,系统对直接父类的初始化步骤也遵循初始化步骤1-3
类的初始化时机(类首次载入Java虚拟机)
创建类的实例
调用类的类方法
访问类或者接口的类变量,或者为该类变量赋值
使用反射方式来强制创建某个类或接口对应的java.lang.Class对象
初始化某个类的子类
直接使用java.exe命令来运行某个主类
2、类加载器:
类加载器的作用:
负责将.class文件加载到内存中,并为之生成对应的 java.lang.Class 对象。
虽然我们不用过分关心类加载机制,但是了解这个机制我们就能更好的理解程序的运行!
JVM的类加载机制:
全盘负责:就是当一个类加载器负责加载某个Class时,该Class所依赖的和引用的其他Class也将由该类加载器负责载入,除非显示使用另外一个类加载器来载入
父类委托:就是当一个类加载器负责加载某个Class时,先让父类加载器试图加载该Class,只有在父类加载器无法加载该类时才尝试从自己的类路径中加载该类
缓存机制:保证所有加载过的Class都会被缓存,当程序需要使用某个Class对象时,类加载器先从缓存区中搜索该Class,只有当缓存区中不存在该Class对象时,系统才会读取该类对应的二进制数据,并将其转换成Class对象,存储到缓存区
Java中的内置类加载器:
ClassLoader:是负责加载类的对象
Bootstrap class loader:它是虚拟机的内置类加载器,通常表示为null ,并且没有父null
Platform class loader:平台类加载器可以看到所有平台类 ,平台类包括由平台类加载器或其祖先定义的Java SE平台API,其实现类和JDK特定的运行时类
System class loader:它也被称为应用程序类加载器 ,与平台类加载器不同。 系统类加载器通常用于定义应用程序类路径,模块路径和JDK特定工具上的类
类加载器的继承关系:System的父加载器为Platform,而Platform的父加载器为Bootstrap
ClassLoader中的两个方法:
static ClassLoader getSystemClassLoader():返回用于委派的系统类加载器
ClassLoader getParent():返回父类加载器进行委派
参考代码:
package com.itheima_01; /* ClassLoader中的两个方法: static ClassLoader getSystemClassLoader():返回用于委派的系统类加载器 ClassLoader getParent():返回父类加载器进行委派 */ public class ClassLoaderDemo { public static void main(String[] args){ //static ClassLoader getSystemClassLoader():返回用于委派的系统类加载器 ClassLoader c = ClassLoader.getSystemClassLoader(); System.out.println(c); //AppClassLoader //ClassLoader getParent():返回父类加载器进行委派 ClassLoader c2 = c.getParent(); System.out.println(c2); //PlatformClassLoader ClassLoader c3 = c2.getParent(); System.out.println(c3); } }
二、反射
1、概述:
Java反射机制:是指在运行时去获取一个类的变量和方法信息。然后通过获取到的信息来创建对象,调用方法的一种机制。由于这种动态性,可以极大的增强程序的灵活性,程序不用在编译期就完成确定,在运行期仍然可以扩展
2、获取Class类的对象:
我们要想通过反射去使用一个类,首先我们要获取到该类的字节码文件对象,也就是类型为Class类型的对象
这里我们提供三种方式获取Class类型的对象:
使用类的class属性来获取该类对应的Class对象。举例:Student.class将会返回Student类对应的Class对象
调用对象的getClass()方法,返回该对象所属类对应的Class对象
该方法是Object类中的方法,所有的Java对象都可以调用该方法
使用Class类中的静态方法forName(String className),该方法需要传入字符串参数,该字符串参数的值是某个类的全路径,也就是完整包名的路径
参考代码:
package com.itheima_02; /* 这里我们提供三种方式获取Class类型的对象: 使用类的class属性来获取该类对应的Class对象。举例:Student.class将会返回Student类对应的Class对象 调用对象的getClass()方法,返回该对象所属类对应的Class对象 该方法是Object类中的方法,所有的Java对象都可以调用该方法 使用Class类中的静态方法forName(String className),该方法需要传入字符串参数,该字符串参数的值是某个类的全路径,也就是完整包名的路径 */ public class ReflectDemo { public static void main(String[] args) throws ClassNotFoundException { //使用类的class属性来获取该类对应的Class对象。 Class<Student> c1 = Student.class; System.out.println(c1); Class<Student> c2 = Student.class; System.out.println(c1 == c2); System.out.println("----------"); //调用对象的getClass()方法,返回该对象所属类对应的Class对象 Student s = new Student(); Class<? extends Student> c3 = s.getClass(); System.out.println(c1 == c3); System.out.println("----------"); //使用Class类中的静态方法forName(String className) Class<?> c4 = Class.forName("com.itheima_02.Student"); System.out.println(c1 == c4); } }
3、反射获取构造方法并使用:
Class类中用于获取构造方法的方法:
Constructor<?>[] getConstructors() :返回所有公共构造方法对象的数组
Constructor<?>[] getDeclaredConstructors():返回所有构造方法对象的数组
Constructor
Constructor类中用于创建对象的方法:
T newInstance(Object...initargs):根据指定的构造方法创建对象
参考代码:
package com.itheima_03; import com.itheima_02.Student; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /* 反射获取构造方法并使用 */ public class ReflectDemo01 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //Constructor<?>[] getConstructors() 返回一个包含 Constructor对象的数组, Constructor对象反映了由该 Class对象表示的类的所有公共构造函数。 // Constructor<?>[] cons = c.getConstructors(); //Constructor<?>[] getDeclaredConstructors() 返回反映由该 Class对象表示的类声明的所有构造函数的 Constructor对象的数组。 Constructor<?>[] cons = c.getDeclaredConstructors(); for(Constructor con : cons){ System.out.println(con); } System.out.println("----------"); //Constructor<T> getConstructor(Class<?>... parameterTypes) 返回一个 Constructor对象,该对象反映由该 Class对象表示的类的指定公共构造函数。 //Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) 返回一个 Constructor对象,该对象反映由此 Class对象表示的类或接口的指定构造函数。 //参数:你要获取构造方法的参数的个数和数据类型对应的字节码文件对象 Constructor<?> con = c.getConstructor(); //Constructor提供了一个类的单个构造函数的信息和访问权限。 //T newInstance(Object... initargs) 使用由此 Constructor对象表示的构造函数,使用指定的初始化参数来创建和初始化构造函数的声明类的新实例。 Object obj = con.newInstance(); System.out.println(obj); /*Student s = new Student(); System.out.println(s);*/ } }
4、反射获取构造方法并使用练习:
练习1:通过反射实现如下操作:
Student s = new Student("林青霞",30,"西安");
System.out.println(s);
注意:基本数据类型也是可以通过.class来获取对应的Class类型
参考代码:
package com.itheima_03; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /* 练习1:通过反射实现如下操作: Student s = new Student("林青霞",30,"西安"); System.out.println(s); */ public class ReflectDemo02 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //获取构造方法对象 //public Student(String name, int age, String address) //Constructor<T> getConstructor(Class<?>... parameterTypes) 返回一个 Constructor对象,该对象反映由该 Class对象表示的类的指定公共构造函数。 //基本数据类型也可通过.class来获取对象的Class Constructor<?> con = c.getConstructor(String.class, int.class, String.class); //构造对象 //T newInstance(Object... initargs) Object obj = con.newInstance("林青霞", 30, "西安"); System.out.println(obj); } }
练习2:通过反射实现如下操作:
Student s = new Student("林青霞");
System.out.println(s);
注意:在反射时使用:public void setAccessible(boolean flag) 值为true时取消访问检查,就可以通过私有构造方法创建对象
参考代码:
package com.itheima_03; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; /* 练习2:通过反射实现如下操作: Student s = new Student("林青霞"); System.out.println(s); */ public class ReflectDemo03 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //Constructor<T> getDeclaredConstructor(Class<?>... parameterTypes) //通过这个方法拿到了私有的构造方法 Constructor<?> con = c.getDeclaredConstructor(String.class); //暴力反射 //public void setAccessible(boolean flag) 值为true时取消访问检查 con.setAccessible(true); Object obj = con.newInstance("林青霞"); System.out.println(obj); } }
5、反射获取成员变量并使用:
Class类中用于获取成员变量的方法:
Field[] getFields() :返回所有公共成员变量对象的数组
Field[] getDeclaredFields() :返回所有成员变量对象的数组
注意:此处的参数为成员变量对应的字段名。
Field getField(String name):返回单个公共成员变量的对象
Field getDeclaredField(String name):返回单个成员变量对象
Field类中用于给成员变量赋值的方法:
void set(Object obj, Object value):给obj对象的成员变量赋值为value
参考代码:
package com.itheima_04; import com.itheima_02.Student; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; /* 反射获取成员变量并使用 */ public class ReflectDemo01 { public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //Field[] getFields() 返回一个包含 Field对象的数组, Field对象反映由该 Class对象表示的类或接口的所有可访问的公共字段。 //Field[] getDeclaredFields() 返回一个 Field对象的数组,反映了由该 Class对象表示的类或接口声明的所有字段。 // Field[] fields = c.getFields(); Field[] fields = c.getDeclaredFields(); for(Field field : fields){ System.out.println(field); } System.out.println("----------"); //获取单个的 //Field getField(String name) 返回一个 Field对象,该对象反映由该 Class对象表示的类或接口的指定公共成员字段。 //Field getDeclaredField(String name) 返回一个 Field对象,该对象反映由该 Class对象表示的类或接口的指定声明字段。 Field addressField = c.getField("address"); //获取无参构造方法创建对象 Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); //A Field提供有关类或接口的单个字段的信息和动态访问。 //void set(Object obj, Object value) 将指定的对象参数中由此 Field对象表示的字段设置为指定的新值。 addressField.set(obj, "西安"); //给obj的成员变量addressField赋值为西安 /*Student s = new Student(); s.address = "西安"; System.out.println(s);*/ System.out.println(obj); } }
6、反射获取成员变量并使用练习:
练习:通过反射实现如下操作:
Student s = new Student();
s.name = "林青霞";
s.age = 30;
s.address = "西安";
System.out.println(s);
参考代码:
package com.itheima_04; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; /* 练习:通过反射实现如下操作: Student s = new Student(); s.name = "林青霞"; s.age = 30; s.address = "西安"; System.out.println(s); */ public class ReflectDemo02 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //通过无参构造方法创建对象 Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); System.out.println(obj); //s.name = "林青霞"; // Field nameField = c.getField("name"); Field nameField = c.getDeclaredField("name"); //暴力处理:取消访问权限检查 nameField.setAccessible(true); nameField.set(obj, "林青霞"); System.out.println(obj); //s.age = 30; Field ageField = c.getDeclaredField("age"); ageField.setAccessible(true); ageField.set(obj, 30); System.out.println(obj); //s.address = "西安"; Field addressField = c.getDeclaredField("address"); addressField.setAccessible(true); addressField.set(obj, "西安"); System.out.println(obj); } }
7、反射获取成员方法并使用:
Class类中用于获取成员方法的方法:
Method[] getMethods() :返回所有公共成员方法对象的数组,包括继承的
Method[] getDeclaredMethods() :放回所有成员方法对象的数组,不包括继承的
Method getMethod(String name, Class... parameterTypes) :返回单个公共成员方法对象 Method getDeclaredMethod(String name, Class... parameterTypes):返回单个成员方法对象
Method类中用于调用成员方法的方法:
Object invoke(Object obj, Object...args):调用obj对象的成员方法,参数时args,返回值时Object类型
参考代码:
package com.itheima_05; import com.itheima_02.Student; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /* 反射获取成员方法并使用 */ public class ReflectDemo01 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //获取成员方法 //Method[] getMethods() 返回一个包含 方法对象的数组, 方法对象反映由该 Class对象表示的类或接口的所有公共方法,包括由类或接口声明的对象以及从超类和超级接口继承的类。 //Method[] getDeclaredMethods() 返回一个包含 方法对象的数组, 方法对象反映由 Class对象表示的类或接口的所有声明方法,包括public,protected,default(package)访问和私有方法,但不包括继承方法。 // Method[] methods = c.getMethods(); //获取类的公共方法,包括父类 Method[] methods = c.getDeclaredMethods(); //不包含继承体系的方法 for(Method method : methods){ System.out.println(method); } System.out.println("----------"); //获取单个方法 //Method getMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象,该对象反映由该 Class对象表示的类或接口的指定公共成员方法。 //Method getDeclaredMethod(String name, Class<?>... parameterTypes) 返回一个 方法对象,它反映此表示的类或接口的指定声明的方法 Class对象。 //public void method1() Method m = c.getMethod("method1");//无参 /*Student s = new Student(); s.method1();*/ //获取无参构造方法创建对象 Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); // obj.m(); //Method在类或接口上提供有关单一方法的信息和访问权限。 //Object invoke(Object obj, Object... args) 在具有指定参数的指定对象上调用此 方法对象表示的基础方法。 //Object:返回值类型;obj:调用方法的对象;Object... args:方法需要的参数 m.invoke(obj); //调用obj对象的m表示的成员方法 } }
8、反射获取成员方法并使用练习:
练习:通过反射实现如下操作:
Student s = new Student();
s.method1();
s.method2("林青霞");
String ss = s.method3("林青霞", 30);
System.out.println(ss);
s.function();
参考代码:
package com.itheima_05; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /* 练习:通过反射实现如下操作: Student s = new Student(); s.method1(); s.method2("林青霞"); String ss = s.method3("林青霞", 30); System.out.println(ss); s.function(); */ public class ReflectDemo02 { public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { //获取Class对象 Class<?> c = Class.forName("com.itheima_02.Student"); //通过无参构造方法创建对象 Constructor con = c.getConstructor(); Object obj = con.newInstance(); //通过对象调用方法 //s.method1(); Method m1 = c.getMethod("method1"); m1.invoke(obj); //s.method2("林青霞"); Method m2 = c.getMethod("method2", String.class); m2.invoke(obj, "林青霞"); //String ss = s.method3("林青霞", 30); //System.out.println(ss); Method m3 = c.getMethod("method3", String.class, int.class); Object o = m3.invoke(obj, "林青霞", 30); System.out.println(o); //s.function(); Method m4 = c.getDeclaredMethod("function"); //设置不再检测权限 m4.setAccessible(true); m4.invoke(obj); } }
9、反射练习:
练习1:我有一个ArrayList
参考代码:
package com.ithiema_06; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList; /* 练习1:我有一个ArrayList<Integer>集合,现在我想在这个集合中添加一个字符串数据,如何实现? */ public class ReflectTest01 { public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { //创建集合 ArrayList<Integer> array = new ArrayList<Integer>(); // array.add(10); // array.add(20); // array.add("hello"); //通过反射实现:反射可以越过泛型检查,使用原始的方法类型 Class<? extends ArrayList> c = array.getClass(); Method m = c.getMethod("add", Object.class); m.invoke(array, "hello"); m.invoke(array, "world"); m.invoke(array, "java"); System.out.println(array); } }
练习2:通过配置文件运行类中的方法
参考代码:
package com.ithiema_06; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.Properties; /* 练习2:通过配置文件运行类中的方法 */ public class ReflectTest02 { public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { /*Student s = new Student(); s.study();*/ /*Teacher t = new Teacher(); t.teach();*/ //此操作后,以后调用类进行变换时只需要需改配置文件即可 /* class.txt className=xxx methodName=xxx */ //加载数据 Properties prop = new Properties(); FileReader fr = new FileReader("myReflect\\class.txt"); prop.load(fr); fr.close(); /* className=com.ithiema_06.Student methodName=study */ String className = prop.getProperty("className"); String methodName = prop.getProperty("methodName"); //通过反射来使用 Class<?> c = Class.forName(className); //com.ithiema_06.Student Constructor<?> con = c.getConstructor(); Object obj = con.newInstance(); Method m = c.getMethod(methodName);//study m.invoke(obj); } }
本文作者:编程初学者求大佬指点
本文链接:https://www.cnblogs.com/fragmentary/p/17008800.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步