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差异赋值,递归算法查找的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2025-01-082024年常用的情绪识别API
- 2025-01-07如何利用看板工具优化品牌内容创作与审批,确保按时发布?
- 2025-01-07百万架构师第十一课:源码分析:Spring 源码分析:Spring源码分析前篇|JavaGuide
- 2025-01-07质量检测标准严苛,这 6 款办公软件达标了吗?
- 2025-01-07提升品牌活动管理的效率:看板工具助力品牌活动日历的可视化管理
- 2025-01-07宠物商场的精准营销秘籍:揭秘看板软件的力量
- 2025-01-07“30了,资深骑手” | 程序员能有什么好出路?
- 2025-01-07宠物公园的营销秘籍:看板软件如何帮你精准触达目标客户?
- 2025-01-07从任务分解到资源优化:甘特图工具全解析
- 2025-01-07企业升级必备指南:从传统办公软件到SaaS工具的转型攻略