在MVC的开发模式中经常需要将model与pojo的数据绑定,apache和spring的工具包中都有BeanUtils,使用其中的copyProperties方法可以非常方便的进行这些工作,但在实际应用中发现,对于null的处理不太符合个人的需要,例如在进行修改操作中只需要对model中某一项进行修改,那么一般我们在页面上只提交model的ID及需要修改项的值,这个时候使用BeanUtils.copyProperties会将其他的null绑定到pojo中去。为解决这个问题我重写了部分spring BeanUtils的代码如下
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) {
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);
}
}
}
}
}
}
apahce的BeanUtils的处理方法类似
分享到:
相关推荐
一个BeanUtils.copyProperties的小型快速替代。 起因 由于BeanUtils(Spring或Apache Commons)的copyProperties实现是利用反射实现的,它在大量调用时具有比较严重的性能问题。 BeanMapper通过javassist类库实现在...
主要介绍了java Beanutils.copyProperties( )用法详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
主要介绍了使用BeanUtils.copyProperties进行对象之间的属性赋值,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
org.apache.commons.beanutils.jar
commons-beanutils-1.8.0.jar beanutils.jar beanutils.jar工具包
关于JSF的commons-beanutils.jar.zip
json相关jar包(不使用springmvc开发时)。其中包含(commons-beanutils.jar、commons-collections-3.1.jar、commons-lang-2.6.jar、commons-logging.jar、ezmorph-1.0.6.jar、json-lib-2.2.3-jdk15.jar)
commons-beanutils.jar commons-beanutils.jar
Apache提供的这个beanutils包极大方便了javabean的 操作。包含了最新的commons-beanutils-1.9.3.jar和api文档,以及其依赖的commons-logging-1.2.jar包
beanUtils 方便访问javaBean 附带支持框架 logging jar包,Apache提供的这个beanutils包极大方便了javabean的 操作。包含了最新的commons-beanutils-1.9.3.jar,以及其依赖的commons-logging-1.2.jar包
这是commons常用到的包,包括:commons-pool.jar,commons-beanutils.jar等共八个commons.jar包
commons-beanutils.jar 开发时所需要的jar包
JSF开发所必需包:花了很长时间才收集好,很费时,现已收集好,何不分享给大家,让大家节省...commons-beanutils.jar commons-collections.jar commons-digester.jar jsf-api.jar jsf-impl.jar jstl.jar standard.jar
此为BeanUtils的实例。其中apache的包有一个小的BUG已在其中说明。
commons-beanutils.jar.zip(173 k)commons-beanutils.jar.zip(173 k)commons-beanutils.jar.zip(173 k) jdbc 专用