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;

    }
}

 

上一篇:LuoguP7852 「EZEC-9」Yet Another Easy Problem 题解


下一篇:yum提示Another app is currently holding the yum lock; waiting for it to exit...