日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【反射的使用】java反射的复习

發布時間:2024/8/5 编程问答 33 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【反射的使用】java反射的复习 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

反射

1.類加載器

1.1類加載

程序要使用一個類需要將類進行加載,連接,初始化

  • 類加載:將class讀入內存,創建一個class對象
  • 類的連接:檢查,協調
  • 類的初始化:如果父類未初始化,會優先初始化父類,再執行子類初始化語句,保證子類的父類都被初始化
  • 反射會強制初始化類,并且初始化的類進入JVM后不會二次加載
  • 1.2類加載器

    Classloader:負責加載類的對象

    機制問題

  • 全盤負責:類加載器會加載該類的所有父類
  • 父類委托:類加載器會先在父類加載器上加載該class,如果無,才直接加載該類
  • 緩存機制:加載的類都會被緩存等待使用
  • 繼承關系

    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的對象

    三種方法進行獲取

  • class屬性:Student.class
  • 調用對象的getClass()方法
  • 靜態方法forName(String className)包含完整的類路徑
  • package com.ljh.reflect02;/*** @Author: ljh* @Date: 2022/1/7 16:08* @Description:測試類*/ public class ReflectDemo {public static void main(String[] args) throws ClassNotFoundException {//class屬性:Student.classClass<Student> c1 = Student.class;System.out.println(c1);//class com.ljh.reflect02.StudentClass<Student> c2 = Student.class;System.out.println(c1==c2);//輸出true表示兩個類相等System.out.println("----");//調用對象的getClass()方法Student student = new Student();Class<? extends Student> c3 = student.getClass();System.out.println(c1==c3);//返回了trueSystem.out.println("----");//靜態方法forName(String className)包含完整的類路徑Class<?> c4 = Class.forName("com.ljh.reflect02.Student");System.out.println(c1==c4);//true} } package com.ljh.reflect02;/*** @Author: ljh* @Date: 2022/1/7 16:00* @Description:學生類*/ public class Student {private String name;int age;public String address;public Student() {}private Student(String name){this.name = name;}Student(String name,int age){this.name = name;this.age = age;}public Student(String name,int age,String address){this.name = name;this.age = age;this.address = address;}private void function(){System.out.println("function");}public void method1(){System.out.println("method");}public void method2(String s){System.out.println("method"+s);}public String method3(String s,int i){return s+","+i;}@Overridepublic String toString() {return "Student{" +"name='" + name + '\'' +", age=" + age +", address='" + address + '\'' +'}';} }

    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.反射獲取成員變量并使用

  • 方法1:Field[] getFields () 返回一個包含Field對象的數組,Field對象反映由該Class對象表示的類或接口的所有可訪問的公共字段
  • 方法2:Field[] getDeclaredFields ()返回一個Field對象的數組,反映了由該Class對象表示的類或接口聲明的所有字段
  • 方法3:Field getField (String name)返回單個公共變量
  • 方法4:Field getDeclaredField(String name)返回單個任意變量
  • 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.反射獲取成員方法并使用

  • Method[ ] getMethods () 返回一個包含方法對象的數組,方法對象反映由該Class對象表示的類或接口的所有公共方法
  • Method[] getDeclaredMethods () 返回一個包含方法對象的數組,方法對象反映由Class對象表示的類或接口的所有聲明的方法
  • getMethods(方法名,參數…)獲取指定方法,使用method的invoke方法調用
  • getDeclaredMethod (方法名,參數…)獲取包含私有方法的所有方法,注意暴力反射
  • package com.ljh.reflect05;import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;/*** @Author: ljh* @Date: 2022/1/8 13:17* @Description:反射獲取成員方法*/ public class ReflectDemo01 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException {//獲取ClassClass<?> aClass = Class.forName("com.ljh.reflect02.Student");//Method[ ] getMethods ()//獲取所有公共方法包含繼承父類的Method[] methods = aClass.getMethods();for (Method m: methods) {System.out.println(m);}System.out.println("------");//Method[] getDeclaredMethods ()//獲取所有本類方法Method[] methods2 = aClass.getDeclaredMethods();for (Method m: methods2) {System.out.println(m);}System.out.println("------");//獲取單個方法Method method1 = aClass.getMethod("method1"); // 做以下操作 // Student student = new Student(); // student.method1();//獲取對象Constructor<?> constructor = aClass.getConstructor();Object o = constructor.newInstance();//使用method的invoke方法method1.invoke(o);//獲取單個私有方法Method method2 = aClass.getDeclaredMethod("function");method2.setAccessible(true);method2.invoke(o);} }

    6.2反射獲取成員方法并使用練習

    通過反射實現以下操作

    Students = new Student();
    s.method1;
    s.method2(“林青霞”);
    String ss = s.method3("林青霞”,30);
    System.out.println(ss); .
    s.function();

    package com.ljh.reflect05;import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method;/*** @Author: ljh* @Date: 2022/1/8 13:42* @Description:練習1*/ public class ReflectDemo02 {public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { // 通過反射實現以下操作Class<?> aClass = Class.forName("com.ljh.reflect02.Student"); // Students = new Student();Constructor<?> constructor = aClass.getConstructor();Object o = constructor.newInstance(); // s.method1;Method method1 = aClass.getMethod("method1");//沒有對象的單獨方法不可調用method1.invoke(o); // s.method2("林青霞");Method method2 = aClass.getMethod("method2", String.class);method2.invoke(o,"林青霞"); // String ss = s.method3("林青霞”,30) // System.out.println(ss);Method method3 = aClass.getMethod("method3", String.class, int.class);String ss = (String) method3.invoke(o,"林青霞",30);System.out.println(ss); // s.function();Method function = aClass.getDeclaredMethod("function");//檢查抑制function.setAccessible(true);//function.invoke(o);} }

    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反射的复习的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。