在開發中經常返現對
user對象轉換其他的user對象時候需要相互轉換時,下面方法可參考:
/**
* 將一個對象轉換爲另一個對象
* @param <T1> 要轉換的對象
* @param <T2> 轉換後的類
* @param orimodel 要轉換的對象
* @param castClass 轉換後的類
* @return 轉換後的對象
*/
public static <T1,T2> T2 convertBean(T1 orimodel, Class<T2> castClass) {
T2 returnModel = null;
try {
returnModel = castClass.newInstance();
} catch (Exception e) {
throw new RuntimeException("創建"+castClass.getName()+"對象失敗");
}
/**要轉換的字段集合*/
List<Field> fieldList = new ArrayList<Field>();
/**循環獲取要轉換的字段,包括父類的字段*/
while (castClass != null &&
!castClass.getName().toLowerCase().equals("java.lang.object")) {
fieldList.addAll(Arrays.asList(castClass.getDeclaredFields()));
/**得到父類,然後賦給自己*/
castClass = (Class<T2>) castClass.getSuperclass();
}
for (Field field : fieldList) {
PropertyDescriptor getpd = null;
PropertyDescriptor setpd = null;
try {
getpd= new PropertyDescriptor(field.getName(), orimodel.getClass());
setpd=new PropertyDescriptor(field.getName(), returnModel.getClass());
} catch (Exception e) {
continue;
}
try {
Method getMethod = getpd.getReadMethod();
Object transValue = getMethod.invoke(orimodel);
Method setMethod = setpd.getWriteMethod();
setMethod.invoke(returnModel, transValue);
} catch (Exception e) {
throw new RuntimeException("cast "+orimodel.getClass().getName()+"to "
+castClass.getName()+" failed");
}
}
return returnModel;
}
也可以用spring自帶的BeanUtils就有這樣的功能,引入spring-beans和spring-core之後,就有BeanUtils.copyProperties(a, b);可以實現兩個javabean之間的相互拷貝,自己寫的就當是研究咯