多くの場合、キャッシュバックの開発における
ユーザオブジェクトがお互いに変換する他の必要性に変換されるときに、ユーザオブジェクトは、次のような方法が参照される場合があり:
/**
* 将一个对象转换为另一个对象
* @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;
}
別のJavaBeanの二つのコピーの間に達成することができる、自分自身を書き込むために、スプリング々BeanUtilsを搬送した後にそのような機能、ばね豆とスプリングコア、そこBeanUtils.copyProperties(B)の導入を持っているにも使用することができます研究はわずかであるとき