日期:2014-05-16 浏览次数:20771 次
import java.beans.PropertyDescriptor; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflexObject { /** * @param root * 源完整类名 * @param target * 目标完整类名 * @param obj_root * 源对象 * @return 目标对象 */ @SuppressWarnings("unchecked") public static Object copyObjectValue(String root, String target, Object obj_root) { Field[] fields = null; try { if (obj_root == null || "null".equals(obj_root) || "".equals(obj_root)) return null; Class cls_root = Class.forName(root); Class cls_target = Class.forName(target); fields = cls_root.getDeclaredFields(); if(!cls_root.isAssignableFrom(cls_target)) fields = cls_target.getDeclaredFields(); Object obj_target = cls_target.newInstance(); for (Field field : fields) { String fieldName = field.getName(); if (fieldName.equalsIgnoreCase("serialVersionUID")) continue; PropertyDescriptor pd_root = new PropertyDescriptor(fieldName, obj_root.getClass()); Method getMethod = pd_root.getReadMethod(); Method setMethod = pd_root.getWriteMethod(); Object o = getMethod.invoke(obj_root); setMethod.invoke(obj_target, o); } return obj_target; } catch (Exception e) { e.printStackTrace(); } return obj_root; } }