1. BeanUtil 类继承了 PropertyUtils 类:源代码:
public class BeanUtil extends PropertyUtils
2. 源代码如下,有小部份中文注释:
/**
* override BeanUtils method copyProperties, support not copy null or blank
* property
*
* @param dest
* @param src
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static void copyProperties(Object dest, Object src) {
// 为两个参数时,skipNull 默认为true
copyProperties(dest, src, true);
}
/**
* override BeanUtils method copyProperties, support not copy null or blank
* property
*
* @param dest
* @param src
* @throws IllegalAccessException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static void copyProperties(Object dest, Object src, boolean skipNull) {
// Validate existence of the specified beans
if (dest == null) {
throw new IllegalArgumentException("No destination bean specified");
}
if (src == null) {
throw new IllegalArgumentException("No origin bean specified");
}
// 获取所有src中的属性,存入于数组中
PropertyDescriptor[] origDescriptors = PropertyUtils
.getPropertyDescriptors(src);
for (int i = 0; i < origDescriptors.length; i++) {
// 取出src中属性名
String name = origDescriptors[i].getName();
if ("class".equals(name)) {
continue; // No point in trying to set an object's class
}
if (PropertyUtils.isReadable(src, name)
&& PropertyUtils.isWriteable(dest, name)) {
Object value = null;
try {
// 取出属性的值
value = PropertyUtils.getSimpleProperty(src, name);
} catch (Exception e) {
throw new RuntimeException();
}
if (skipNull) {
if (value == null) {
continue;
}
} else if (value == null){
value = null;
}
try {
//copyProperties(dest, name, value);
setProperty(dest, name, value);
} catch (Exception e) {
throw new RuntimeException();
}
}
}
}
使用方法很简单。