Java反射获取字段的属性值及对比两个对象的属性值null差异赋值,递归算法查找
2021/11/29 1:06:09
本文主要是介绍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; } }
这篇关于Java反射获取字段的属性值及对比两个对象的属性值null差异赋值,递归算法查找的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-09-21订单系统资料入门教程:轻松管理你的订单
- 2024-09-21Java部署资料:新手入门教程
- 2024-09-21Java部署资料:新手入门教程
- 2024-09-21Java订单系统资料:新手入门教程与实战指南
- 2024-09-21Java管理系统资料入门教程
- 2024-09-21从零开始学习Java监控系统资料
- 2024-09-21Java就业项目资料:新手入门的必备教程
- 2024-09-21Java全端资料:初学者指南
- 2024-09-21Java全栈资料入门教程及资源汇总
- 2024-09-21Java日志系统资料入门教程