Java 对象字段属性差异对比工具类 (修改前&修改后的属性值)
2021/6/10 12:21:10
本文主要是介绍Java 对象字段属性差异对比工具类 (修改前&修改后的属性值),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
工具类: ContrastObjUtil
import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; import com.alibaba.fastjson.JSONArray; import com.alibaba.fastjson.JSONObject; /** * 属性差异 工具类 */ public class ContrastObjUtil { public static String comparObj(Object oldBean, Object newBean) { JSONArray array = new JSONArray(); try { Class clazz = oldBean.getClass(); Field[] fields = oldBean.getClass().getDeclaredFields(); int i = 1; for (Field field : fields) { if ("serialVersionUID".equals(field.getName())) { continue; } PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz); Method getMethod = pd.getReadMethod(); Object o1 = getMethod.invoke(oldBean); Object o2 = getMethod.invoke(newBean); if (o1 == null || o2 == null) { continue; } if (!o1.toString().equals(o2.toString())) { // 要显示的字段名 String fieldName = ""; fieldName = field.getName(); JSONObject json = new JSONObject(); json.put("type", fieldName); json.put("oldValue", o1); json.put("newValue", o2); array.add(json); i++; } } } catch (Exception e) { e.printStackTrace(); } return array.toJSONString(); } }
测试:
public void testCompare(){ User u1 = new User(); u1.setId(1); u1.setName("小明"); u1.setPhone("12580"); User u2 = new User(); u2.setId(1); u2.setName("小明"); u2.setPhone("12580999"); String result = ContrastObjUtil.comparObj(u1, u2); System.out.println(result);//[{"newValue":"12580999","oldValue":"12580","type":"phone"}] }
结果:
[{"newValue":"12580999","oldValue":"12580","type":"phone"}]
这篇关于Java 对象字段属性差异对比工具类 (修改前&修改后的属性值)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-06-26结对编程到底难不难?答案在这里
- 2024-06-19《2023版Java工程师》课程升级公告
- 2024-06-15matplotlib作图不显示3D图,怎么办?
- 2024-06-1503-Loki 日志监控
- 2024-06-1504-让LLM理解知识 -Prompt
- 2024-06-05做软件测试需要懂代码吗?
- 2024-06-0514-ShardingSphere的分布式主键实现
- 2024-06-03为什么以及如何要进行架构设计权衡?
- 2024-05-31全网首发第二弹!软考2024年5月《软件设计师》真题+解析+答案!(11-20题)
- 2024-05-31全网首发!软考2024年5月《软件设计师》真题+解析+答案!(21-30题)