类拷贝
业务上,有model和entity之分,但他们之间的成员变量名大多相同,所以,在做数据更新时,如果一个一个的GS会很麻烦,还好Spring有一个叫做BeanUtil的工具包可用,但是它所拷贝的,是只要名字相同就值替换,但是有时候我只需要将新值覆盖原值即可,空值不操作,所以就仿写了一份:
public class BeanUtils extends org.springframework.beans.BeanUtils { private BeanUtils() { } /** * 实体类复制,只复制非空字段 * * @param source 源类 * @param target 目标类 */ public static void copyNullProperties(Object source, Object target) { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); Class<?> actualEditable = target.getClass(); PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); for (PropertyDescriptor targetPd : targetPds) { Method writeMethod = targetPd.getWriteMethod(); try { if (writeMethod != null) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null) { Method readMethod = sourcePd.getReadMethod(); if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) { if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); if (null == value) continue; if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } } } catch (Throwable ex) { throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", ex); } } } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· Ollama——大语言模型本地部署的极速利器
· 使用C#创建一个MCP客户端
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· Windows编程----内核对象竟然如此简单?
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
2016-06-28 Java设置session超时(失效)的三种方式
2016-06-28 JAVA开发Web Service几种框架介绍