BeanUtils(前端赋值给后台,忽略空属性)
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 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 | package com.drn.core.util; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Set; import org.springframework.beans.BeansException; import org.springframework.beans.FatalBeanException; import org.springframework.util.Assert; public abstract class BeanUtils extends org.springframework.beans.BeanUtils { public static void copyProperties(Object source, Object target) throws BeansException { 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) { if (targetPd.getWriteMethod() != null ) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null ) { try { Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible( true ); } Object value = readMethod.invoke(source); // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等 if (value != null ) { boolean isEmpty = false ; if (value instanceof Set) { Set s = (Set) value; if (s == null || s.isEmpty()) { isEmpty = true ; } } else if (value instanceof Map) { Map m = (Map) value; if (m == null || m.isEmpty()) { isEmpty = true ; } } else if (value instanceof List) { List l = (List) value; if (l == null || l.size() < 1 ) { isEmpty = true ; } } else if (value instanceof Collection) { Collection c = (Collection) value; if (c == null || c.size() < 1 ) { isEmpty = true ; } } if (!isEmpty) { Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible( true ); } writeMethod.invoke(target, value); } } } catch (Throwable ex) { throw new FatalBeanException( "Could not copy properties from source to target" , ex); } } } } } } |
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步