在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的处理方法类似
分享到:
相关推荐
4. **复制属性**: `BeanUtils.copyProperties()`方法可以将一个JavaBean的属性值复制到另一个JavaBean中,这在创建对象的副本或者进行对象间的数据迁移时非常有用。 5. **集合操作**: BeanUtils还支持与集合对象...
在1.8.0版本中,BeanUtils Core进行了如下改进和增强: 1. 错误处理:对于无法转换的数据类型或不存在的属性,提供了更友好的错误提示和处理机制,使得开发者能更快定位问题。 2. 性能优化:通过对内部算法的优化...
3. **复制属性**:BeanUtils.copyProperties()方法可以将一个JavaBean的所有属性值复制到另一个具有相同属性的JavaBean中,这对于对象克隆或数据迁移非常有用。 4. **异常处理**:BeanUtils在遇到无法处理的属性或...
1. **属性复制**:BeanUtils.copyProperties()方法允许你将一个对象的所有属性值复制到另一个对象。这在你需要创建对象副本或者在不同对象间同步数据时非常有用。 2. **反射调用**:通过反射机制,BeanUtils能直接...
《Apache Commons BeanUtils 1.8.3:深入解析与应用》 Apache Commons BeanUtils是Apache软件基金会开发的一个Java库,它提供了一种方便、灵活的方式来操作JavaBeans。这个库的核心功能是通过反射和属性访问机制,...
《BeanUtils库详解及其在Java开发中的应用》 在Java开发中,BeanUtils是一个非常重要的工具库,它是由Apache Commons项目提供的,主要用于处理Java Bean对象的属性操作。本篇文章将详细解析BeanUtils库的核心功能,...
例如,`BeanUtils.copyProperties()`方法现在能够更好地处理目标Bean的泛型属性,自动转换源Bean的属性值,确保类型匹配。这使得在Bean复制过程中,开发者无需手动进行类型转换,减少了潜在的错误。 此外,Spring4...
- **Web开发**:在Servlet或JSP应用中,`commons-beanutils`常用于模型视图的绑定,将请求参数映射到Bean对象。 - **数据转换**:在数据交换或序列化过程中,BeanUtils的属性拷贝功能能帮助快速地转换数据结构。 ...
《Apache Commons BeanUtils 1.8.3:深入解析与应用》 Apache Commons BeanUtils是Apache软件基金会开发的一个Java库,它提供了一种方便、灵活的方式来操作JavaBeans。在这个特定的压缩包“commons-beanutils-1.8.3...