溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Java反射中的類有哪些

發(fā)布時(shí)間:2022-01-30 10:25:16 來(lái)源:億速云 閱讀:151 作者:iii 欄目:開(kāi)發(fā)技術(shù)

本文小編為大家詳細(xì)介紹“Java反射中的類有哪些”,內(nèi)容詳細(xì),步驟清晰,細(xì)節(jié)處理妥當(dāng),希望這篇“Java反射中的類有哪些”文章能幫助大家解決疑惑,下面跟著小編的思路慢慢深入,一起來(lái)學(xué)習(xí)新知識(shí)吧。

    一、什么是反射

    java.lang包提供java語(yǔ)言程序設(shè)計(jì)的基礎(chǔ)類,在lang包下存在一個(gè)子包:reflect,與反射相關(guān)的APIs均在此處;

    官方對(duì)reflect包的介紹如下:

    Reflection enables Java code to discover information about the fields, methods and constructors of loaded classes, and to use reflected fields, methods, and constructors to operate on their underlying counterparts, within security restrictions.
    The API accommodates applications that need access to either the public members of a target object (based on its runtime class) or the members declared by a given class. It also allows programs to suppress default reflective access control.

    java.lang.reflect官方介紹

    簡(jiǎn)單來(lái)說(shuō),反射機(jī)制就像類對(duì)照平靜的湖面,湖面映射出類的字段、方法、構(gòu)造函數(shù)等信息;反射機(jī)制不僅可以看到類信息,還能針對(duì)字段、方法等做出相應(yīng)的操作。

    二、準(zhǔn)備測(cè)試:實(shí)體類的創(chuàng)建

    為方便解釋說(shuō)明,首先創(chuàng)建一個(gè)實(shí)體類,用于測(cè)試使用

    package cn.byuan.entity;
    
    /**
     * 學(xué)生實(shí)體類
     *
     * @author byuan
     * @date 2022-01-25
     */
    public class Student {
    
        /**
         * 學(xué)生學(xué)號(hào), 公共變量, 默認(rèn)值: defaultStudentNo
         * */
        public String studentNo = "defaultStudentNo";
    
        /**
         * 學(xué)生姓名, 公共變量, 默認(rèn)值: defaultStudentName
         * */
        public String studentName = "defaultStudentName";
    
        /**
         * 學(xué)生性別, 私有變量, 默認(rèn)值: defaultStudentSex
         * */
        private String studentSex = "defaultStudentSex";
    
        /**
         * 學(xué)生年齡, 私有變量, 默認(rèn)值: 0
         * */
        private Integer studentAge = 0;
    
        /**
         * 公有無(wú)參構(gòu)造方法
         * */
        public Student() {
    
        }
    
        /**
         * 公有滿參構(gòu)造方法
         * */
        public Student(String studentNo, String studentName, String studentSex, Integer studentAge) {
            this.studentNo = studentNo;
            this.studentName = studentName;
            this.studentSex = studentSex;
            this.studentAge = studentAge;
        }
    
        /**
         * 私有構(gòu)造方法
         * */
        private Student(String studentSex, Integer studentAge) {
            this.studentSex = studentSex;
            this.studentAge = studentAge;
        }
    
        /**
         * get/set 方法
         * */
        public String getStudentNo() {
            return studentNo;
        }
    
        public Student setStudentNo(String studentNo) {
            this.studentNo = studentNo;
            return this;
        }
    
        public String getStudentName() {
            return studentName;
        }
    
        public Student setStudentName(String studentName) {
            this.studentName = studentName;
            return this;
        }
    
        public String getStudentSex() {
            return studentSex;
        }
    
        public Student setStudentSex(String studentSex) {
            this.studentSex = studentSex;
            return this;
        }
    
        public Integer getStudentAge() {
            return studentAge;
        }
    
        public Student setStudentAge(Integer studentAge) {
            this.studentAge = studentAge;
            return this;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "studentNo = " + this.studentNo + ", " +
                    "studentName = " + this.studentName + ", " +
                    "studentSex = " + this.studentSex + ", " +
                    "studentAge = " + this.studentAge +"}";
        }
    
        /**
         * 學(xué)生類說(shuō)話方法
         * */
        private String speak(String message) {
            return this.studentName + " : " + message;
        }
    
    }

    三、反射中的幾個(gè)重要類及方法

    在了解反射前,先來(lái)梳理下一個(gè)類(Class)本身中包含了哪些內(nèi)容。

    • 字段,字段又由修飾符、字段類型、字段名稱、對(duì)應(yīng)值等部分組成

    • 構(gòu)造方法,構(gòu)造方法可簡(jiǎn)單分為無(wú)參與有參兩大類

    • 非構(gòu)造方法,又稱普通方法,方法由修飾符、返回值類型、方法名、形參表、方法體等部分構(gòu)成

    本文所論述的反射中幾個(gè)重要類及其對(duì)應(yīng)方法正基于以上內(nèi)容

    (一)反射中的重要類之Class

    Class類代表了類本身,類本身包含字段,構(gòu)造方法,非構(gòu)造方法等內(nèi)容,因此使用反射的第一步就是獲取對(duì)象所對(duì)應(yīng)的Class類。

    僅就使用反射而言,我們需著重了解Class類的獲取方式,下面給出實(shí)例

    1. Class類測(cè)試實(shí)例

    package cn.byuan.example;
    import cn.byuan.entity.Student;
    /**
     * 獲取 Class 的幾種方式
     *
     * @author byuan
     * @date 2022-01-25
     */
    public class GetClassExample {
        public static void main(String[] args) throws ClassNotFoundException {
            // 獲取 class 方式一: 通過(guò)類的全路徑字符串獲取 Class 對(duì)象
            Class getClassExample1 = Class.forName("cn.byuan.entity.Student");
            // 獲取 class 方式二: 通過(guò)類名直接獲取
            Class getClassExample2 = Student.class;
            // 獲取 class 方式三: 通過(guò)已創(chuàng)建的對(duì)象獲取對(duì)應(yīng) Class
            Student student1 = new Student();
            Class getClassExample3 = student1.getClass();
        }
    }

    (二)反射中的重要類之Field

    Field類是對(duì)類中屬性的描述,借助Class與Field的配合,我們可以了解類中有哪些字段,并做出相應(yīng)處理;

    1. Field類的獲取與常用方法

    Class類為我們提供了兩個(gè)方法用以獲取Field類:

    • getDeclaredFields():獲取所有聲明的字段(包括公有字段和私有字段)

    • getFields():僅可獲取公有字段

    Field類代表了類中的屬性字段,常用類中屬性字段可籠統(tǒng)分為兩種,公有字段(public)與私有字段(private);

    每個(gè)字段又具有四個(gè)屬性:修飾符,字段類型,字段名稱,對(duì)應(yīng)值;Field也自然提供了對(duì)應(yīng)方法對(duì)這四種屬性進(jìn)行獲?。?/p>

    • getModifiers():獲取字段修飾符相加值,想要獲取明確標(biāo)識(shí)需要通過(guò)Modifier常量的toString方法對(duì)相加值進(jìn)行解碼

    • getType():獲取字段類型

    • getName():獲取字段名稱

    • get(Object):獲取字段對(duì)應(yīng)值

    下面給出實(shí)例

    2. Field類測(cè)試實(shí)例

    package cn.byuan.example;
    
    import cn.byuan.entity.Student;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    
    /**
     * 獲取類字段的幾種方式
     *
     * @author byuan
     * @date 2021-01-25
     */
    public class GetFieldExample {
        public static void main(String[] args) throws IllegalAccessException {
            Class studentClass = Student.class;
            // 獲取類字段的兩個(gè)方法: getDeclaredFields, getFields
            // 1. getDeclaredFields: 獲取所有聲明的字段(包括公有字段和私有字段)
            Field[] declaredFieldArray = studentClass.getDeclaredFields();
            printFieldInformation(declaredFieldArray);
            // 2. getFields: 僅可獲取公有字段
            Field[] fieldArray = studentClass.getFields();
            printFieldInformation(fieldArray);
            // 獲取字段對(duì)應(yīng)值
            Student student = new Student()
                    .setStudentSex("女")
                    .setStudentAge(18);
            printFieldValue(student);
        }
    
        /**
         * 打印類字段信息
         *
         * @param fieldArray 類字段對(duì)象列表
         * */
        public static void printFieldInformation(Field[] fieldArray) {
            for (Field fieldPart : fieldArray) {
                System.out.println("直接打印類字段對(duì)象: " + fieldPart);
                // 獲取字段修飾符
                String fieldModifier = Modifier.toString(fieldPart.getModifiers());
                // 獲取字段類型
                String fieldType = fieldPart.getType().getName();
                // 獲取字段名稱
                String fieldName = fieldPart.getName();
                System.out.println(fieldModifier + " " + fieldType + " " + fieldName);
            }
            System.out.println();
        }
    
        /**
         * 打印類字段屬性
         *
         * @param t 泛型對(duì)象
         * */
        private static <T> void printFieldValue(T t) throws IllegalAccessException {
            Field[] fieldValueArray = t
                    .getClass()
                    .getDeclaredFields();
            for (Field fieldValuePart : fieldValueArray) {
                // 對(duì)于有可能存在的 private 字段取消語(yǔ)言訪問(wèn)檢查
                fieldValuePart.setAccessible(true);
                // 字段名稱
                String filedName = fieldValuePart.getName();
                // 字段對(duì)應(yīng)值
                String fieldValue = fieldValuePart.get(t).toString();
                System.out.println(filedName + " = " + fieldValue);
            }
        }
    }

    運(yùn)行截圖

    Java反射中的類有哪些

    (三)反射中的重要類之Constructor

    Constructor代表了某個(gè)類的構(gòu)造方法,是用來(lái)管理所有的構(gòu)造函數(shù)的類

    1. Constructor類的獲取與常用方法

    Class類為我們提供了兩個(gè)方法用以獲取Constructor類:

    1. getDeclaredConstructors():獲取所有構(gòu)造方法

    2. getConstructors():僅可獲取公有構(gòu)造方法

    對(duì)于構(gòu)造器,可簡(jiǎn)單將其分為兩大類,無(wú)參構(gòu)造器與帶參構(gòu)造器,構(gòu)造器也是方法的一種,因此對(duì)于任意一構(gòu)造器都由修飾符,方法名,形參表,方法體四部分組成;Constructor自然也為其組成部分提供了對(duì)應(yīng)方法:

    1. 與字段類似,Constructors同樣提供了getModifiers()方法:獲取構(gòu)造器修飾符相加值,想要獲取明確標(biāo)識(shí)需要通過(guò)Modifier常量的toString方法進(jìn)行解碼

    2. getName():獲取構(gòu)造器名稱

    3. getParameterTypes():獲取構(gòu)造器參數(shù)列表

    下面給出實(shí)例

    2. Constructor類測(cè)試實(shí)例

    package cn.byuan.example;
    import cn.byuan.entity.Student;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.Modifier;
    
    /**
     * 獲取構(gòu)造方法的幾種方式
     *
     * @author byuan
     * @date 2022-01-25
     */
    public class GetConstructorsExample {
        public static void main(String[] args) {
            Class studentClass = Student.class;
            // 獲取類構(gòu)造器的兩個(gè)方法: getDeclaredConstructors, getConstructors
            // 1. getDeclaredConstructors: 獲取所有構(gòu)造方法
            Constructor[] declaredConstructorArray = studentClass.getDeclaredConstructors();
            printConstructorInformation(declaredConstructorArray);
            // 2. getConstructors, 僅可獲取公有構(gòu)造方法
            Constructor[] constructorArray = studentClass.getConstructors();
            printConstructorInformation(constructorArray);
        }
    
        /**
         * 打印構(gòu)造器信息
         *
         * @param constructorArray 構(gòu)造器對(duì)象列表
         * */
        public static void printConstructorInformation(Constructor[] constructorArray) {
            for (Constructor constructorPart : constructorArray) {
                System.out.println("直接打印構(gòu)造器對(duì)象: " + constructorPart);
                // 獲取構(gòu)造器修飾符
                String constructorModifier = Modifier.toString(constructorPart.getModifiers());
                // 獲取構(gòu)造器名稱
                String constructorName = constructorPart.getName();
                // 獲取構(gòu)造器參數(shù)列表
                Class[] constructorParameterArray = constructorPart.getParameterTypes();
                // 打印構(gòu)造器參數(shù)列表
                System.out.print(constructorModifier + " " + constructorName + "(");
                for (Class constructorParameterPart : constructorParameterArray) {
                    System.out.print(constructorParameterPart.getName() + " ");
                }
                System.out.println(")");
            }
            System.out.println();
        }
    }

    運(yùn)行截圖

    Java反射中的類有哪些

    3. 利用Constructor類實(shí)例化對(duì)象

    一般而言,我們關(guān)心的不只是獲取到對(duì)象構(gòu)造器的具體信息,更重要的是如何利用反射實(shí)例化對(duì)象,針對(duì)對(duì)象實(shí)例化,Constructor提供了兩種類型的方法:

    1. getConstructor(Class<?>... parameterTypes):獲取指定形參表的構(gòu)造方法,可借助其獲取無(wú)參/指定參數(shù)的構(gòu)造方法;

    2. newInstance(Object ... initargs):通過(guò)形參表傳遞實(shí)例化對(duì)象參數(shù),與getConstructor配合使用;

    注意:Class也存在newInstance()方法,但僅能用來(lái)調(diào)用類的無(wú)參構(gòu)造器

    4. Constructor實(shí)例化對(duì)象測(cè)試實(shí)例

    package cn.byuan.example;
    import cn.byuan.entity.Student;
    import java.lang.reflect.Constructor;
    import java.lang.reflect.InvocationTargetException;
    
    /**
     * 構(gòu)造器調(diào)用實(shí)例
     *
     * @author byuan
     * @date 2022-01-26
     */
    public class ConstructorsInvokeExample {
        public static void main(String[] args) throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
            Class studentClass = Student.class;
            // Class 類的 newInstance 方法
            studentClass.newInstance();
            // 1. 調(diào)用公有無(wú)參構(gòu)造器
            Object object1 = studentClass
                    .getConstructor()
                    .newInstance();
            System.out.println(object1.getClass());
            // 2. 調(diào)用公有滿參構(gòu)造器
            Constructor studentConstructorFull = studentClass
                    .getConstructor(String.class, String.class, String.class, Integer.class);
            Object object2 = studentConstructorFull
                    .newInstance("2022001", "趙一", "男", 18);
            System.out.println(object2);
            // 3. 調(diào)用私有構(gòu)造器
            Constructor studentConstructorPrivate = studentClass
                    .getDeclaredConstructor(String.class, Integer.class);
            // 私有構(gòu)造器需將 accessible 設(shè)置為 true, 取消語(yǔ)言訪問(wèn)檢查
            studentConstructorPrivate.setAccessible(true);
            Object object3 = studentConstructorPrivate
                    .newInstance("女", 19);
            System.out.println(object3);
        }
    }

    運(yùn)行截圖

    Java反射中的類有哪些

    (四)反射中的重要類之Method

    Method類描述了類的方法信息

    1. Method類的獲取與常用方法

    Class類為我們提供了兩個(gè)方法用以獲取Method類:

    1. getDeclaredMethods():獲取所有非構(gòu)造方法

    2. getMethods():僅可獲取公有非構(gòu)造方法

    對(duì)于任意方法都可分為修飾符,方法名,形參表,方法體四部分;Method為其組成部分提供了對(duì)應(yīng)方法:

    1. getModifiers():獲取方法修飾符相加值,想要獲取明確標(biāo)識(shí)需要通過(guò)Modifier常量的toString方法進(jìn)行解碼

    2. getName():獲取方法名稱

    3. getParameterTypes():獲取方法形參表

    2. Method類測(cè)試實(shí)例

    package cn.byuan.example;
    import cn.byuan.entity.Student;
    import java.lang.reflect.Method;
    import java.lang.reflect.Modifier;
    
    /**
     * 獲取非構(gòu)造方法的幾種方式
     *
     * @author byuan
     * @date 2022-01-26
     */
    public class GetMethodExample {
        public static void main(String[] args) {
            Class studentClass = Student.class;
            // 獲取非構(gòu)造方法的兩個(gè)方法: getDeclaredMethods, getMethods
            // 1. getDeclaredMethods: 獲取所有非構(gòu)造方法
            Method[] declaredMethodArray = studentClass.getDeclaredMethods();
            printMethodInformation(declaredMethodArray);
            // 2. getMethods, 僅可獲取公有非構(gòu)造方法
            Method[] methodArray = studentClass.getMethods();
            printMethodInformation(methodArray);
        }
    
        /**
         * 打印非構(gòu)造器方法信息
         *
         * @param methodArray 構(gòu)造器對(duì)象列表
         * */
        public static void printMethodInformation(Method[] methodArray) {
            for (Method methodPart : methodArray) {
                System.out.println("直接打印非構(gòu)造方法對(duì)象: " + methodArray);
                // 獲取非構(gòu)造器方法修飾符
                String methodModifier = Modifier.toString(methodPart.getModifiers());
                // 獲取非構(gòu)造器方法名稱
                String methodName = methodPart.getName();
                String methodReturnType = methodPart.getReturnType().getName();
                // 獲取非構(gòu)造方法參數(shù)列表
                Class[] constructorParameterArray = methodPart.getParameterTypes();
                // 打印非構(gòu)造方法參數(shù)列表
                System.out.print(methodModifier + " " + methodReturnType + " " + methodName + "(");
                for (Class methodParameterPart : constructorParameterArray) {
                    System.out.print(methodParameterPart.getName() + " ");
                }
                System.out.println(")");
            }
            System.out.println();
        }
    }

    運(yùn)行截圖

    Java反射中的類有哪些

    3. 利用Method調(diào)用非構(gòu)造方法

    與利用Constructor實(shí)例化對(duì)象相似,Method同樣需要兩個(gè)方法用以調(diào)用非構(gòu)造方法

    1. getDeclaredMethod(方法名, 形參表數(shù)組): 獲取所有構(gòu)造方法

    2. invoke(對(duì)象實(shí)例, 參數(shù)數(shù)組):方法調(diào)用

    4. Method調(diào)用非構(gòu)造方法測(cè)試實(shí)例

    package cn.byuan.example;
    import cn.byuan.entity.Student;
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    
    /**
     * 非構(gòu)造器方法調(diào)用實(shí)例
     *
     * @author byuan
     * @date 2022-01-26
     */
    public class MethodInvokeExample {
        public static void main(String[] args) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, InstantiationException {
            Class studentClass = Student.class;
            // 對(duì)于私有的非構(gòu)造方法, 需要使用 getDeclaredMethod 進(jìn)行獲取
            // getDeclaredMethod(方法名, 形參表數(shù)組)
            Method studentSpeakMethod = studentClass.getDeclaredMethod("speak", new Class[]{String.class});
            // 取消語(yǔ)言訪問(wèn)檢查
            studentSpeakMethod.setAccessible(true);
            // invoke(對(duì)象實(shí)例, 參數(shù)數(shù)組)
            Object object = studentSpeakMethod.invoke(studentClass.newInstance(), "Hello, world");
            System.out.println(object);
        }
    }

    運(yùn)行截圖

    Java反射中的類有哪些

    四、綜合實(shí)戰(zhàn):利用反射機(jī)制編寫對(duì)象拷貝工具類

    在實(shí)際項(xiàng)目中,我們經(jīng)常會(huì)遇到POJO與VO等類型對(duì)象進(jìn)行相互轉(zhuǎn)換的情況,如果直接進(jìn)行轉(zhuǎn)換則會(huì)使用大量的樣板代碼,為消除這樣的代碼,我們可以寫一個(gè)簡(jiǎn)單的對(duì)象拷貝工具類進(jìn)行解決;

    (一)業(yè)務(wù)分析

    通過(guò)反射獲取源對(duì)象Field數(shù)組,并利用Field類提供的set/get方法實(shí)現(xiàn)同名屬性的拷貝;

    (二)實(shí)體類準(zhǔn)備

    創(chuàng)建Student類

    package cn.byuan.entity;
    
    /**
     * 學(xué)生實(shí)體類
     *
     * @author byuan
     * @date 2022-01-25
     */
    public class Student {
    
        /**
         * 學(xué)生學(xué)號(hào), 公共變量, 默認(rèn)值: defaultStudentNo
         * */
        public String studentNo = "defaultStudentNo";
    
        /**
         * 學(xué)生姓名, 公共變量, 默認(rèn)值: defaultStudentName
         * */
        public String studentName = "defaultStudentName";
    
        /**
         * 學(xué)生性別, 私有變量, 默認(rèn)值: defaultStudentSex
         * */
        private String studentSex = "defaultStudentSex";
    
        /**
         * 學(xué)生年齡, 私有變量, 默認(rèn)值: 0
         * */
        private Integer studentAge = 0;
    
        /**
         * 公有無(wú)參構(gòu)造方法
         * */
        public Student() {
    
        }
    
        /**
         * 公有滿參構(gòu)造方法
         * */
        public Student(String studentNo, String studentName, String studentSex, Integer studentAge) {
            this.studentNo = studentNo;
            this.studentName = studentName;
            this.studentSex = studentSex;
            this.studentAge = studentAge;
        }
    
        /**
         * 私有構(gòu)造方法
         * */
        private Student(String studentSex, Integer studentAge) {
            this.studentSex = studentSex;
            this.studentAge = studentAge;
        }
    
        public String getStudentNo() {
            return studentNo;
        }
    
        public Student setStudentNo(String studentNo) {
            this.studentNo = studentNo;
            return this;
        }
    
        public String getStudentName() {
            return studentName;
        }
    
        public Student setStudentName(String studentName) {
            this.studentName = studentName;
            return this;
        }
    
        public String getStudentSex() {
            return studentSex;
        }
    
        public Student setStudentSex(String studentSex) {
            this.studentSex = studentSex;
            return this;
        }
    
        public Integer getStudentAge() {
            return studentAge;
        }
    
        public Student setStudentAge(Integer studentAge) {
            this.studentAge = studentAge;
            return this;
        }
    
        @Override
        public String toString() {
            return "Student{" +
                    "studentNo = " + this.studentNo + ", " +
                    "studentName = " + this.studentName + ", " +
                    "studentSex = " + this.studentSex + ", " +
                    "studentAge = " + this.studentAge +"}";
        }
    
        /**
         * 學(xué)生類說(shuō)話方法
         * */
        private String speak(String message) {
            return this.studentName + " : " + message;
        }
    }

    創(chuàng)建StudentOut類

    package cn.byuan.api.out;
    
    import cn.byuan.entity.Student;
    
    /**
     * 學(xué)生類出參
     *
     * @author byuan
     * @date 2022-01-26
     */
    public class StudentOut {
        /**
         * 學(xué)生學(xué)號(hào), 公共變量
         * */
        private String studentNo;
    
        /**
         * 學(xué)生姓名, 公共變量
         * */
        private String studentName;
    
        /**
         * 學(xué)生性別, 私有變量
         * */
        private String studentSex;
    
        /**
         * 學(xué)生年齡, 私有變量
         * */
        private Integer studentAge;
    
        public String getStudentNo() {
            return studentNo;
        }
    
        public StudentOut setStudentNo(String studentNo) {
            this.studentNo = studentNo;
            return this;
        }
    
        public String getStudentName() {
            return studentName;
        }
    
        public StudentOut setStudentName(String studentName) {
            this.studentName = studentName;
            return this;
        }
    
        public String getStudentSex() {
            return studentSex;
        }
    
        public StudentOut setStudentSex(String studentSex) {
            this.studentSex = studentSex;
            return this;
        }
    
        public Integer getStudentAge() {
            return studentAge;
        }
    
        public StudentOut setStudentAge(Integer studentAge) {
            this.studentAge = studentAge;
            return this;
        }
    
        @Override
        public String toString() {
            return "StudentOut{" +
                    "studentNo = " + this.studentNo + ", " +
                    "studentName = " + this.studentName + ", " +
                    "studentSex = " + this.studentSex + ", " +
                    "studentAge = " + this.studentAge +"}";
        }
    }

    (三)工具類編寫

    package cn.byuan.util;
    import cn.byuan.api.out.StudentOut;
    import cn.byuan.entity.Student;
    import java.lang.reflect.Field;
    
    /**
     * 對(duì)象屬性拷貝工具類
     *
     * @author byuan
     * @date 2022-01-26
     */
    public class BeanUtil {
        /**
         * 對(duì)象拷貝工具
         *
         * @param sourceObject 源對(duì)象
         * @param destClass 目的對(duì)象對(duì)應(yīng) Class
         *
         * @return 拷貝完畢后對(duì)象
         * */
        public static <T> T copyObject(Object sourceObject, Class<T> destClass) {
            if (sourceObject == null) {
                return null;
            }
    
            try {
    
                T destObject = destClass.newInstance();
    
                copyField(sourceObject, destObject);
    
                return destObject;
    
            } catch (InstantiationException e) {
                e.printStackTrace();
                
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                
            } catch (Exception e) {
                e.printStackTrace();
            }
            return null;
        }
    
    
        /**
         * 對(duì)象屬性拷貝工具
         *
         * @param sourceObject 源對(duì)象
         * @param destObject 目的對(duì)象
         * */
        private static void copyField(Object sourceObject, Object destObject) {
            if (sourceObject == null || destObject == null) {
                return;
            }
    
            // 獲取源對(duì)象所有字段
            Field[] sourceFieldArray = sourceObject.getClass().getDeclaredFields();
            for (Field sourceFieldPart : sourceFieldArray) {
                // 取消語(yǔ)言訪問(wèn)檢查
                sourceFieldPart.setAccessible(true);
                String sourceFieldName = sourceFieldPart.getName();
                try {
                    // 根據(jù)屬性名稱獲取目標(biāo)對(duì)象對(duì)應(yīng)類字段
                    Field destField = destObject
                            .getClass()
                            .getDeclaredField(sourceFieldName);
                    destField.setAccessible(true);
                    destField.set(destObject, sourceFieldPart.get(sourceObject));
                } catch (NoSuchFieldException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
    
        }
    
        public static void main(String[] args) {
            Student student = new Student("2022001", "趙一", "男", 18);
            StudentOut studentOut = copyObject(student, StudentOut.class);
            System.out.println(studentOut);
        }
    }

    運(yùn)行截圖

    Java反射中的類有哪些

    讀到這里,這篇“Java反射中的類有哪些”文章已經(jīng)介紹完畢,想要掌握這篇文章的知識(shí)點(diǎn)還需要大家自己動(dòng)手實(shí)踐使用過(guò)才能領(lǐng)會(huì),如果想了解更多相關(guān)內(nèi)容的文章,歡迎關(guān)注億速云行業(yè)資訊頻道。

    向AI問(wèn)一下細(xì)節(jié)

    免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

    AI