protected void 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); json.put(paramName, "instance."+methodName+"()"); } } 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 (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } }
現在問題就是這里:json.put(paramName, userClass.getMethod(methodName, null));我獲取不了getXXX()值的,json? put進去的時候只是一竄方法名,如:{"name":"public java.lang.String b2c.members.model.Member.getName()"}
Java 如何獲取一個未知對象類型的getXXX()方法的值
慕田峪9158850
2018-12-06 23:30:24
