最近做PO和DO的相互转换,由于事先不知道apache的beanutils和dozer两种方式,故自己写了一个简单的工具类。由于后来考虑到自己写的工具类也不支持bean属性为对象时克隆功能,所以最后弃用,使用dozer来进行java bean转换。
现附上原先的工具类:
public static Object Convert(Object objs, Object objt){
if(objs!=null&&objt!=null){
Class sCls = objs.getClass();
Class tCls = objt.getClass();
Field[] tFld = tCls.getDeclaredFields();
for(Field fld:tFld){//Traversing the DO object properties
String fileName = fld.getName();
String firstLetter = fileName.substring(0,1).toUpperCase();//the first letter must be upper
String setMehtodName = "set"+firstLetter+fileName.substring(1);
String getMethodName = "get"+firstLetter+fileName.substring(1);
try {
Method getMethod = sCls.getMethod(getMethodName, new Class[]{});
Object value = getMethod.invoke(objs, new Object[]{});
Method setMethod = tCls.getMethod(setMehtodName, new Class[]{fld.getType()});
setMethod.invoke(objt, new Object[]{value});
} catch (NoSuchMethodException e) {
logger.info("the DO Object have not this property "+fileName, e);
} catch (Exception e) {
logger.info("converting occurs wrong ",e);
}
}
return objt;
}
return null;
}
本文介绍了一种用于JavaBean转换的简单工具类实现过程,包括如何遍历目标对象属性并进行属性复制的方法。该工具类虽不支持复杂类型的属性复制,但提供了基本的JavaBean之间的转换功能。
1773

被折叠的 条评论
为什么被折叠?



