/** * 拷贝属性到目标对象,如果为空不拷贝,目标对象属性有值,则不拷贝该属性 * * @param source * 待拷贝属性的对象 * @param target * 目标对象 * @throws BeansException */ public static void copyPropertiesExclude(Object source, Object target) throws BeansException { if (source == null || target == null) { throw new RuntimeException("拷贝和被拷贝对象不能为空。"); } 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) { Method targetReadMethod = targetPd.getReadMethod(); if (!Modifier.isPublic(targetReadMethod.getDeclaringClass().getModifiers())) { targetReadMethod.setAccessible(true); } Object targetValue = targetReadMethod.invoke(target); Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } if(targetValue!=null && !StringUtils.isEmpty(targetValue.toString()) && !"[]".equals(targetValue.toString())){ continue; } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); } } } } }
拷贝对象属性
原创
©著作权归作者所有:来自51CTO博客作者BrightAries的原创作品,谢绝转载,否则将追究法律责任
上一篇:poi 导出word,导出表格(复杂表格合并行列)解决方法
下一篇:我的友情链接
提问和评论都可以,用心的回复会被更多人看到
评论
发布评论
相关文章
-
对象属性的拷贝extend
很多时候我们在处理对象的时候都在做一件同样的事情----将某一个源对象的
js-object extend 目标对象