Java不同类的属性拷贝(通过泛型和反射实现)

由于项目用到了WebService,客户端是用cxf自动生成的代码,有时候服务端的类对象,要转换到客户端的类对象上面去,而两者不是同一个类对象,但字段大体相似。总是通过setXXX(getXXX())总是显得有些臃肿和浪费时间,所以写了一个通过的方法,来实现转化,也实现了泛型。供参考,在赋值这一块,我只验证了二者的类型,没有做类型转换。

  1. public static T copyProperty(H sourceObj, Class targetClass) {
  2. try {
  3. T targetObj = targetClass.newInstance();
  4. Field[] targetFields = targetClass.getDeclaredFields();
  5. Field[] sourceFields = sourceObj.getClass().getDeclaredFields();
  6. PropertyDescriptor sfpd = null;
  7. Method readMehtod = null;
  8. PropertyDescriptor tfpd = null;
  9. Method setMethod = null;
  10. for (Field targetField : targetFields) {
  11. for (Field sourceField : sourceFields) {
  12. if (targetField.getName().equals(sourceField.getName())) {
  13. sfpd = new PropertyDescriptor(sourceField.getName(), sourceObj.getClass());
  14. readMehtod = sfpd.getReadMethod();
  15. tfpd = new PropertyDescriptor(targetField.getName(), targetClass);
  16. setMethod = tfpd.getWriteMethod();
  17. // 这里只是粗略地做了一下判断...
  18. if (readMehtod.getReturnType().equals(setMethod.getParameterTypes()[0])) {
  19. setMethod.invoke(targetObj, readMehtod.invoke(sourceObj));
  20. }
  21. }
  22. }
  23. }
  24. return targetObj;
  25. } catch (Exception e) {
  26. return null;
  27. }
  28. }
  29. [人物存档]【HoneySelect2】【捏脸数据】

 Java不同类的属性拷贝(通过泛型和反射实现)_第1张图片

点击下载(谷歌云盘):http://raboninco.com/18MGr

你可能感兴趣的:(Java不同类的属性拷贝(通过泛型和反射实现))