e.FLY

将集合中的对象所有get方法序列化为json格式
/**
   * 将集合中的对象所有get方法序列化为json格式
   * @author E.FLY
   * @date 2012-4-7
   * @time 上午01:45:02
   * @param collection
   */
  public String mySerializeJosnForAjax(Collection<?> collection){
   JSONArray array = new JSONArray();
   JSONObject js = new JSONObject();
   try {
    if(collection.size()>0){
     for (Object object : collection) {
      JSONObject json = new JSONObject();
//      Object instance = null;
      Class<?> userClass = Class.forName(object.getClass().getName());  //返回与带有给定字符串名的类或接口相关联的 Class 对象
//      instance = userClass.newInstance();  // 创建此 Class 对象所表示的类的一个新实例。
//      instance = myReferenceObject(object);
      Method[] methods = userClass.getMethods();//获得该类的所有方法
      for (Method method : methods) {
       String methodName = method.getName();//获得方法名
       if(methodName.substring(0,3).equals("get")){//获得"get"方法
        //获取属性名 setName
        String paramName = methodName.substring(3,4).toLowerCase()+methodName.substring(4);
        Object invoke = method.invoke(object, null);
        json.put(paramName, invoke);
       }
      }
      array.put(json);
     }
     
     js.put("total",total);
              js.put("page",page);
              js.put("rp",rp);
              js.put("sortname",sortname);
              js.put("sortorder",sortorder);
              
              js.put("rows", array);
    }else{
              js.put("rows", "none");
             }
   } catch (Exception e) {
    e.printStackTrace();
   }
   
   return js.toString();
  }
  
  /**
   * 反射出指定类型的对象
   * @author E.FLY
   * @date 2012-4-7
   * @time 上午01:29:08
   * @param obj
   * @return
   */
  @SuppressWarnings("unused")
  public Object myReferenceObject(Object obj){
   Object newObj= null;
   try {
    Class<?> c = obj.getClass();
    //创建此类型的空对象  
    Field fu = Unsafe.class.getDeclaredField("theUnsafe");
    fu.setAccessible(true);  
    Unsafe us = (Unsafe) fu.get(null);  
    newObj = us.allocateInstance(c);
    
    //获取所有成员(包括private)的值,并拷贝到新对象中  
    Field[] fields = c.getDeclaredFields();  
    for (Field f : fields) {  
     //不拷贝static成员和final成员  
     if (Modifier.isStatic(f.getModifiers()) || Modifier.isFinal(f.getModifiers())) {  
      continue;  
     }  
     //设置成员变量访问权  
     f.setAccessible(true);  
     Object fieldValue = f.get(obj);  
     f.set(newObj, fieldValue);  
    } 

   } catch (Exception e) {
    e.printStackTrace();
   } 
   return newObj;
  }

 

 

posted on 2012-04-11 22:56  e.FLY  阅读(540)  评论(0)    收藏  举报