利用反射 复制一个对象

   public static Object copy(Object obj) throws Exception{ 
      Class<?> classType = obj.getClass();
      // 利用无参构造一个对象
      Object copyOj = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
      // 获取源对象的属性数组
      Field[] fields = classType.getDeclaredFields();
       // 遍历数组 进行赋值
      for (Field f :fields){
       String fieldName = f.getName();
       String fristChar = fieldName.substring(0,1).toUpperCase();
       String setMethodName ="set"+fristChar+fieldName.substring(1);
       String getMethodName = "get"+fristChar+fieldName.substring(1);
       Method setMethod = classType.getDeclaredMethod(setMethodName, new Class[]{f.getType()});
       Method getMethod = classType.getDeclaredMethod(getMethodName, new Class[]{});
       Object result = getMethod.invoke(obj);
       setMethod.invoke(copyOj, new Object[]{result});
      }
      return copyOj;
   }
posted @ 2014-08-28 10:58  god bless you  阅读(371)  评论(0编辑  收藏  举报