首页 > 其他 > 详细

利用反射 复制一个对象

时间:2014-08-28 12:47:40      阅读:311      评论:0      收藏:0      [点我收藏+]
   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;
   }

利用反射 复制一个对象

原文:http://www.cnblogs.com/sunny89/p/3941109.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!