【反射的使用】java反射的复习
反射
1.類加載器
1.1類加載
程序要使用一個類需要將類進行加載,連接,初始化
1.2類加載器
Classloader:負責加載類的對象
機制問題
繼承關系
Bootstrap內置加載器->Platform class loader平臺加載器->System class loader應用程序加載器
兩個方法
package com.ljh.reflect;/*** @Author: ljh* @Date: 2022/1/7 15:39* @Description: 使用ClassLoader的兩個方法*/ public class ClassLoaderDemo {public static void main(String[] args) {//返回用于委派的系統類加載器ClassLoader c = ClassLoader.getSystemClassLoader();System.out.println(c);//sun.misc.Launcher$AppClassLoader@18b4aac2//返回它的父類ClassLoader c2 = c.getParent();System.out.println(c2);//sun.misc.Launcher$ExtClassLoader@7f31245a//返回它的父類ClassLoader c3 = c2.getParent();System.out.println(c3);//null} }2.反射概述
反射就是,比如學生類被類加載器轉為.class文件,在代碼中Class就是這個類的影像,可以通過Class類里面的方法調用學生類里面的成員變量,構造方法,成員方法等
3.獲取Class的對象
三種方法進行獲取
4.反射獲取構造方法并使用
方法1:返回所有公共構造方法的數組 getConstructors()
方法2:返回所有公共和私有構造方法的數組getDeclaredConstructors()
方法3:返回指定的公共構造方法 getConstructor(Class<?>,parameterTypes),并用newInstance對該類new一個對象
方法4:返回指定的公共或私有構造方法 getDeclaredConstructor(Class<?>,parameterTypes),注意私有方法使用暴力反射public void setAccessible (boolean flag):值為true取消訪問檢查
package com.ljh.reflect03;import com.ljh.reflect02.Student;import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;/*** @Author: ljh* @Date: 2022/1/7 16:46* @Description:獲取構造方法*/ public class ReflectDemo01 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//對學生類進行類加載Class<?> c1 = Class.forName("com.ljh.reflect02.Student");//getConstructors(),只能返回公共構造方法Constructor<?>[] constructors = c1.getConstructors();for (Constructor con: constructors) {System.out.println(con);//public com.ljh.reflect02.Student(java.lang.String,int,java.lang.String)//public com.ljh.reflect02.Student()}System.out.println("-----");//使用getDeclaredConstructors();返回所有類型構造方法Constructor<?>[] constructors2 = c1.getDeclaredConstructors();for (Constructor con: constructors2) {System.out.println(con); // public com.ljh.reflect02.Student(java.lang.String,int,java.lang.String) // com.ljh.reflect02.Student(java.lang.String,int) // private com.ljh.reflect02.Student(java.lang.String) // public com.ljh.reflect02.Student()}System.out.println("----");//使用 getConstructor()找到指定的構造方法并用newInstance對該類new一個對象Constructor<?> c4 = c1.getConstructor();Object o = c4.newInstance();System.out.println(o);//Student{name='null', age=0, address='null'}} }4.1.1反射獲取構造方法練習1
package com.ljh.reflect03;import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;/*** @Author: ljh* @Date: 2022/1/7 20:29* @Description:練習1*/ public class ReflectDemo02 {/* 通過反射實現如下的操作: Student s = new Student( "林青霞", 30,“西安"); System.out.println(s); */public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//思路學生類全賦值需要 public Student(String name,int age,String address)方法//先創建ClassClass<?> aClass = Class.forName("com.ljh.reflect02.Student");//獲取構造方法Constructor<?> constructor = aClass.getConstructor(String.class, int.class, String.class);//基本數據類型也可以直接classObject o = constructor.newInstance("林青霞", 30, "西安");System.out.println(o);//Student{name='林青霞', age=30, address='西安'}} }4.1.2反射獲取構造方法練習2
package com.ljh.reflect03;import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException;/*** @Author: ljh* @Date: 2022/1/7 20:39* @Description:練習2*/ public class ReflectDemo03 {/* 通過反射實現如下的操作: Student s = new Student( "林青霞"); System.out.println(s); */public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//思路: 使用私有構造方法private Student(String name)Class<?> aClass = Class.forName("com.ljh.reflect02.Student");//獲取私有構造方法,如果按照公共構造方法new私有對象會報錯Constructor<?> declaredConstructor = aClass.getDeclaredConstructor(String.class);//因此加入暴力反射//public void setAccessible (boolean flag):值為true取消訪問檢查declaredConstructor.setAccessible(true);//不信可以注銷這句再運行會報錯Object o = declaredConstructor.newInstance("林青霞");//Student{name='林青霞', age=0, address='null'}System.out.println(o);} }5.反射獲取成員變量并使用
Field:利用Field中set(obj,field)對其進行賦值操作
package com.ljh.reflect04;import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException;/*** @Author: ljh* @Date: 2022/1/7 20:49* @Description:反射獲取成員變量并使用*/ public class ReflectDemo01 {public static void main(String[] args) throws ClassNotFoundException, NoSuchFieldException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//1.獲取Class對象Class<?> aClass = Class.forName("com.ljh.reflect02.Student");//2.1Field[] getFields () 返回一個包含Field對象的數組,Field對象反映由該Class對象表示的類或接口的所有可訪問的公共字段Field[] fields1 = aClass.getFields();for (Field f: fields1) {System.out.println(f);}System.out.println("----");//2.2Field[] getDeclaredFields ()返回一個Field對象的數組,反映了由該Class對象表示的類或接口聲明的所有字段Field[] fields2 = aClass.getDeclaredFields();for (Field f: fields2) {System.out.println(f);}System.out.println("----");//2.3.1Field getField (String name)返回單個公共變量Field field1 = aClass.getField("address");System.out.println(field1);//2.3.2使用set方法對obj進行賦值操作Constructor<?> constructor = aClass.getConstructor();Object o = constructor.newInstance();//賦值field1.set(o,"西安");System.out.println(o);System.out.println("----");//Field getDeclaredField(String name)返回單個任意變量Field field2 = aClass.getDeclaredField("name");System.out.println(field2);System.out.println("----"); // 執行結果 // public java.lang.String com.ljh.reflect02.Student.address // ---- // private java.lang.String com.ljh.reflect02.Student.name // int com.ljh.reflect02.Student.age // public java.lang.String com.ljh.reflect02.Student.address // ---- // public java.lang.String com.ljh.reflect02.Student.address // Student{name='null', age=0, address='西安'} // ---- // private java.lang.String com.ljh.reflect02.Student.name // ----} }5.1反射獲取成員變量并使用的練習
package com.ljh.reflect04;import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException;/*** @Author: ljh* @Date: 2022/1/7 21:22* @Description:練習*/ public class Reflect05 {//使用反射獲取如下操作://Students = new Student(;//s.name = "林青霞;//s.age = 30;//s.address = "西安";//System.out.println(s);public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//獲取ClassClass<?> aClass = Class.forName("com.ljh.reflect02.Student");//獲取構造方法(公共)Constructor<?> constructor = aClass.getConstructor();//創建對象Object o = constructor.newInstance();//獲取三個成員變量Field[] declaredFields = aClass.getDeclaredFields();//賦值nameField field1 = declaredFields[0];//因為name私有,暴力反射field1.setAccessible(true);field1.set(o,"林青霞");//賦值ageField field2 = declaredFields[1];//暴力反射field2.setAccessible(true);field2.set(o,18);//賦值公共變量地址Field field3 = declaredFields[2];field3.set(o,"西安");System.out.println(o);//Student{name='林青霞', age=18, address='西安'}} }6.反射獲取成員方法并使用
6.2反射獲取成員方法并使用練習
通過反射實現以下操作
Students = new Student();
s.method1;
s.method2(“林青霞”);
String ss = s.method3("林青霞”,30);
System.out.println(ss); .
s.function();
7.反射練習之越過泛型檢查
練習1:我有一個ArrayList 集合,現在我想在這個集合中添加一個字符串數據,如何實現?
package com.ljh.reflect06;import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.ArrayList;/*** @Author: ljh* @Date: 2022/1/8 14:00* @Description:反射越過泛型檢查*/ public class ReflectDemo01 {//練習1:我有一個ArrayList <Integer>集合,現在我想在這個集合中添加一個字符串數據,如何實現?public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {//正常情況ArrayList<Integer> integers = new ArrayList<>();integers.add(1);integers.add(2);for (int i:integers) {System.out.println(i);}System.out.println("-----");//1.找到ClassClass<? extends ArrayList> aClass = integers.getClass();//2.找到add方法Method add = aClass.getDeclaredMethod("add", Object.class);//3.抑制檢查add.setAccessible(true);//4.使用add.invoke(integers,"hahaha");//5.輸出結果System.out.println(integers.get(2));} }8.反射之使用配置文件
練習2:通過配置文件運行類中的方法(準備學生類和老師類)
package com.ljh.reflect06;/*** @Author: ljh* @Date: 2022/1/8 14:11* @Description:*/ public class Student {public void study(){System.out.println("好好學習,天天向上");} } package com.ljh.reflect06;/*** @Author: ljh* @Date: 2022/1/8 14:11* @Description:*/ public class Teacher {public void teach(){System.out.println("用愛成就學員");} } package com.ljh.reflect06;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;/*** @Author: ljh* @Date: 2022/1/8 14:13* @Description:*/ public class ReflectDemo02 {public static void main(String[] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//在class.txt文件中使用我們的方法 // className = xxx // methodName = xxx//加載數據Properties properties = new Properties();FileReader fileReader = new FileReader("src\\com\\ljh\\reflect06\\class.txt");properties.load(fileReader);fileReader.close();String className = properties.getProperty("className");String methodName = properties.getProperty("methodName");//反射開始,class默認學生類Class<?> aClass = Class.forName(className);//創建對象調用方法Constructor<?> constructor = aClass.getConstructor();Object o = constructor.newInstance();//Method method = aClass.getMethod(methodName);method.invoke(o);//要改變只需要更改配置文件就可以} }總結
以上是生活随笔為你收集整理的【反射的使用】java反射的复习的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【idea中debug的使用】
- 下一篇: 【java】StringBuilder的