由于项目用到了WebService,客户端是用cxf自动生成的代码,有时候服务端的类对象,要转换到客户端的类对象上面去,而两者不是同一个类对象,但字段大体相似。总是通过setXXX(getXXX())总是显得有些臃肿和浪费时间,所以写了一个通过的方法,来实现转化,也实现了泛型。供参考,在赋值这一块,我只验证了二者的类型,没有做类型转换。
public static <T, H> T copyProperty(H sourceObj, Class targetClass) { try { T targetObj = targetClass.newInstance(); Field[] targetFields = targetClass.getDeclaredFields(); Field[] sourceFields = sourceObj.getClass().getDeclaredFields(); PropertyDescriptor sfpd = null; Method readMehtod = null; PropertyDescriptor tfpd = null; Method setMethod = null; for (Field targetField : targetFields) { for (Field sourceField : sourceFields) { if (targetField.getName().equals(sourceField.getName())) { sfpd = new PropertyDescriptor(sourceField.getName(), sourceObj.getClass()); readMehtod = sfpd.getReadMethod(); tfpd = new PropertyDescriptor(targetField.getName(), targetClass); setMethod = tfpd.getWriteMethod(); // 这里只是粗略地做了一下判断... if (readMehtod.getReturnType().equals(setMethod.getParameterTypes()[0])) { setMethod.invoke(targetObj, readMehtod.invoke(sourceObj)); } } } } return targetObj; } catch (Exception e) { return null; } }