Java反射獲取字段的屬性值及對比兩個對象的屬性值null差異賦值,遞歸算法查找


package com.example.demo;

import java.lang.reflect.Field;

/**
 * 需求描述:同一類的不同對象,如果某個字段的null則從另外的一個對象中賦值。
 */
public class StudentTest {

    //靜態內部類
    static class Student {
        private String name;
        private String sex;
        private String password;

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + name + '\'' +
                    ", sex='" + sex + '\'' +
                    ", password='" + password + '\'' +
                    '}';
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public String getSex() {
            return sex;
        }

        public void setSex(String sex) {
            this.sex = sex;
        }

        public String getPassword() {
            return password;
        }

        public void setPassword(String password) {
            this.password = password;
        }
    }

    public static void main(String[] args) throws Exception{
        Student student = new Student();
        student.setName("劉德華");
        student.setPassword(null);
        student.setSex(null);

        Student another = new Student();
        another.setPassword("778899");
        another.setSex("男");

        find(student,another,"name");
        find(student,another,"password");
        find(student,another,"sex");
        System.out.println("student=" + student.toString());

        find(another,student,"name");
        find(another,student,"password");
        find(another,student,"sex");
        System.out.println("another=" + another.toString());


    }

    public static String find(Student student,Student another,String filedName) throws Exception{
        Field[] stuField = student.getClass().getDeclaredFields();
        Field[] anotherField = another.getClass().getDeclaredFields();

        for (int i=0;i< stuField.length;i++){
            //Student with modifiers "private"
            stuField[i].setAccessible(true);
            anotherField[i].setAccessible(true);
            if(stuField[i].getName().equals(filedName)){
                if(stuField[i].get(student) == null){
                    //解決兩個對象的某屬性都同時為null的情況
                    if(anotherField[i].get(another) != null) {
                        /**
                         * 遞歸算法
                         */
                        String filedNameValue = find(another, student, filedName);
                        stuField[i].set(student, filedNameValue);
                    }
                    break;
                }else{
                    return (String)stuField[i].get(student);
                }
            }
        }
        return null;

    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM