Java工具类
BeanUtils.copyProperties排除null属性的copy
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 | import com.hourumiyue.system.SpringUtil; import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanWrapper; import org.springframework.beans.BeanWrapperImpl; import org.springframework.beans.BeansException; import org.springframework.context.ApplicationContext; import org.springframework.context.ApplicationContextAware; import java.util.HashSet; import java.util.Set; public class TestBeanUtiles { public static String[] getNullPropertyNames (Object source) { final BeanWrapper src = new BeanWrapperImpl(source); java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors(); Set<String> emptyNames = new HashSet<String>(); for (java.beans.PropertyDescriptor pd : pds) { Object srcValue = src.getPropertyValue(pd.getName()); if (srcValue == null ) emptyNames.add(pd.getName()); } String[] result = new String[emptyNames.size()]; return emptyNames.toArray(result); } //封装同名称属性复制,但是空属性不复制过去 public static void copyPropertiesIgnoreNull(Object src, Object target){ BeanUtils.copyProperties(src, target, getNullPropertyNames(src)); } public static void main(String[] args) { NewPerson newPerson = new NewPerson(); newPerson.setName( "miyue" ); //前台用户更新过的数据,例如前台只修改了用户名 //下面我们假设是从数据库加载出来的老数据 OldPerson oldPerson = new OldPerson(); oldPerson.setSex( "nv" ); oldPerson.setAge( 5 ); //如果我们想把新数据更新到老数据这个对象里面,我们就可以借助BeanUtils.copyProperties()的方法如下: //BeanUtils.copyProperties(newPerson, oldPerson); copyPropertiesIgnoreNull(newPerson, oldPerson); System.out.println(newPerson.toString()); System.out.println(oldPerson.toString()); } } |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!