自己实现的apache beanUtil
写这段代码之前不知道有beanUtil可以实现实体bean之间相同属性值的copy。。。不过听说apache那个解决date类型字段处理比较麻烦,我这个没这个问题,而且还能父类copy到子类,子类copy到父类。
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;}}