SpringFramework BeanUtil

在使用SpringMVC开发JavaWeb网站的时候,当执行Update方法的时候,需要对修改实体类的字段进行set操作,字段过多的时候一个个的set实在是一件麻烦事,于是想到了SpringFramework自带的BeanUtils方法,但是这个方法会将结果为Null的字段也进行拷贝,与实际Update功能不符,因此需要进行改写。

Quick Start

改写SpringFramework 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
package com.cloud.util;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;

public class BeanUtil {

private BeanUtil(){}

/**
* 重写工具类BeanUtils,如果为NULL则不复制属性值
* @param source newClass
* @param target oldClass
*/
public static void copyProperties(Object source,Object target){
BeanUtils.copyProperties(source, target,getNullPropertyNames(source));
}

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);
}

}

结束

在实际使用过程中可以进行拓展,比如对int类型进行操作。

Fiveplus wechat
扫一扫上方二维码,关注微信公众号:阿五编程
如果这篇文章对你有所帮助,请点击下方的打赏按钮。