下面是一个利用反射操作bean的工具类。
实现功能:
- 拷贝对象属性;
- 拷贝指定属性;
- 设置属性;
- 获取属性;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import org.apache.commons.lang.StringUtils;
/**
* 将一个对象的属性值拷贝到另一个类或者对象对应属性中
* 属性 名及类型要匹配 并且 源对象属性要提供getter方法 目标对象属性要提供setter方法
*/
public class BeansUtil {
/**
* 拷贝属性
*
* @param sourceObj 源对象
* @param targetClass 目标类
* @return
*/
public static Object copyProperties(Object sourceObj, Class<?> targetClass)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
Object targetObj = Class.forName(targetClass.getName()).newInstance();
return copyProperties(sourceObj, targetObj);
}
/**
* 拷贝对象属性
*
* @param sourceObj 源对象
* @param targetObj 目标对象
* @return
*/
public static Object copyProperties(Object sourceObj, Object targetObj) {
if (sourceObj == null) {
throw new IllegalArgumentException("sourceObj is null");
}
if (targetObj == null) {
throw new IllegalArgumentException("targetObj is null");
}
Field[] targetFields = targetObj.getClass().getDeclaredFields();
if (targetFields.length == 0) {
return targetObj;
}
for (int i = 0; i < targetFields.length; i++) {
copyProperty(sourceObj, targetObj, targetFields[i].getName());
}
return targetObj;
}
/**
* 拷贝指定的对象属性
*
* @param sourceObj
* @param targetObj
* @param copyFields 指定的对象属性
* @return
*/
public static Object copyProperties(Object sourceObj, Object targetObj, String[] copyFields) {
if (sourceObj == null) {
throw new IllegalArgumentException("sourceObj is null");
}
if (targetObj == null) {
throw new IllegalArgumentException("targetObj is null");
}
if (copyFields == null || copyFields.length <= 0) {
return targetObj;
}
Field[] targetFields = targetObj.getClass().getDeclaredFields();
if (targetFields.length == 0) {
return targetObj;
}
for (int i = 0; i < copyFields.length; i++) {
copyProperty(sourceObj, targetObj, copyFields[i]);
}
return targetObj;
}
//PropertyDescriptor内部已经自动处理了is get的情况
public static void copyProperty(Object sourceObj, Object targetObj, String name) {
if (sourceObj == null || targetObj == null || StringUtils.isBlank(name)) {
return;
}
try {
Object value = getProperty(sourceObj, name);
setProperty(targetObj, name, value);
} catch (Exception e) {
}
}
public static void setProperty(Object object, String name, Object value) throws Exception {
if (object == null || StringUtils.isBlank(name)) {
return;
}
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, object.getClass());
propertyDescriptor.getWriteMethod().invoke(object, value);
}
//PropertyDescriptor内部已经自动处理了is get的情况
public static Object getProperty(Object object, String name) throws Exception {
if (object == null || StringUtils.isBlank(name)) {
return null;
}
PropertyDescriptor propertyDescriptor = new PropertyDescriptor(name, object.getClass());
return propertyDescriptor.getReadMethod().invoke(object);
}
}