记录代码:复制对象的值,回到一个新的实例

记录代码:复制对象的值,返回一个新的实例
业务需要,要把一个对象中的值封装到另一个对象中。所以自己写了一个转换工具,而没使用BeanUtils.copyProperties()。
以后可以参考类似思路进行Vo、Bo、Po等封装类的转换。

代码例子如下,仅列出大概思路:
public class VoConvertUtil {

/**
* 将指定Vo中的属性值转移到另一个Vo中,只有相同名称的属性才能转移
*
* @param desObj
*            目标Vo对象,可以是一个new出的实例
* @param srcObj
*            源Vo对象
* @return 转移后的新Vo对象
* @throws 自行封装的Exception
*/
public static Object convertVoToVo(Object desObj, Object srcObj)
throws 自行封装的Exception {
BeanInfo bi = null;
Method method = null;
try {
bi = Introspector.getBeanInfo(desObj.getClass());
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
String methodName = "get"
+ pd.getName().substring(0, 1).toUpperCase()
+ pd.getName().substring(1);
try {
method = srcObj.getClass().getDeclaredMethod(methodName);
} catch (NoSuchMethodException e) {
continue;
}
Object srcValue = method.invoke(srcObj);
if (null != srcValue && null != pd.getWriteMethod()
&& !"getClass".equals(methodName)) {
pd.getWriteMethod().invoke(desObj, srcValue);
} else {
continue;
}
}
} catch (IntrospectionException e) {
throw new 自行封装的Exception(e);
} catch (SecurityException e) {
throw new 自行封装的Exception(e);
} catch (IllegalArgumentException e) {
throw new 自行封装的Exception(e);
} catch (IllegalAccessException e) {
throw new 自行封装的Exception(e);
} catch (InvocationTargetException e) {
throw new 自行封装的Exception(e);
}
return desObj;
}

public static Object formatVoPropertyToBlank(Object vo)
throws 自行封装的Exception {
BeanInfo bi = null;
try {
bi = Introspector.getBeanInfo(vo.getClass());
PropertyDescriptor[] pds = bi.getPropertyDescriptors();
for (PropertyDescriptor pd : pds) {
Object propertyValue = pd.getReadMethod().invoke(vo);
if (null == propertyValue) {
if ("class java.lang.String".equals(pd.getPropertyType()
.toString())) {
pd.getWriteMethod().invoke(vo, "");
} else if ("class java.math.BigDecimal".equals(pd.getPropertyType()
.toString())) {
pd.getWriteMethod().invoke(vo, new BigDecimal(0));
}
} else {
continue;
}
}
} catch (IntrospectionException e) {
throw new 自行封装的Exception(e);
} catch (IllegalArgumentException e) {
throw new 自行封装的Exception(e);
} catch (IllegalAccessException e) {
throw new 自行封装的Exception(e);
} catch (InvocationTargetException e) {
throw new 自行封装的Exception(e);
}
return vo;
}

}