2012-08-07 75 views
1

首先代码:法提取,泛型,反射

Bond[] bonds = null; 
    try 
    { 
     JSONArray jsonArray = new JSONArray(result); 
     bonds = new Bond[jsonArray.length()]; 
     for (int i = 0; i < jsonArray.length(); i++) 
     { 
      JSONObject json = jsonArray.getJSONObject(i); 
      bonds[i] = new Bond(json); 
     } 
    } 
    catch (JSONException e) 
    { 
     e.printStackTrace(); 
    } 

二:

Announcement[] announcements = null; 
    try 
    { 
     JSONArray jsonArray = new JSONArray(result); 
     announcements = new Announcement[jsonArray.length()]; 
     for (int i = 0; i < jsonArray.length(); i++) 
     { 
      JSONObject json = jsonArray.getJSONObject(i); 
      announcements[i] = new Announcement(json); 
     } 
    } 
    catch (JSONException e) 
    { 
     e.printStackTrace(); 
    } 

我想提取,这将覆盖这两个码的方法。我认为方法应该或多或少是这样的:

static Object[] getObjectsArray(String jsonString, Class<?> cls) 
{ 
    Object[] objects = null; 
    try 
    { 
     JSONArray jsonArray = new JSONArray(jsonString); 
     objects = (Object[]) Array.newInstance(cls, jsonArray.length()); 
     for (int i = 0; i < jsonArray.length(); i++) 
     { 
      JSONObject json = jsonArray.getJSONObject(i); 
      objects[i] = new Announcement(json); // FIXME: How to pass "json" arg to the constructor with cls.newInstance()? 
     } 
    } 
    catch (JSONException e) 
    { 
     e.printStackTrace(); 
    } 
    return objects; 
} 

所以后来取代第一代码,我可以叫Bond[] bonds = (Bond[]) getObjectsArray(jsonArray, Bond)

这是最容易出问题的线路:

objects[i] = new Announcement(json); // FIXME: How to pass "json" arg to the constructor with cls.newInstance()? 

回答

1

您可以使用下面的语法使用与参数的构造函数(我假设的构造函数的参数是一个JSONObject和构造是公共 - 如果它不,使用getDeclaredConstructor法):

Class<Announcement> cls = Announcement.class; //the second argument of your method 
objects[i] = cls.getConstructor(JSONObject.class).newInstance(json); 
+0

难道不应该是“公告。类”? – 2012-08-07 13:06:00

+0

'cls = Announcement.class'和'cls.getDeclaredConstructor(JSONObject.class)'得到Announcement的构造函数,它将JSONObject作为参数(除非我将其混合?)。 – assylias 2012-08-07 13:09:14

+0

哦,等一下。你是对的!抱歉。这可能是最好的,如果你表明'cls'是Announcement.class – 2012-08-07 13:10:30

1

可以使用泛型类型提供安全,避免铸件,你将不得不虽然返回一个列表。

static <T> List<T> getObjectsArray(String jsonString, Class<T> cls) { 
     ... 
} 

如果你有公告绑定之间的通用类型(接口),这将是很好开往泛型类型是这样的:

static <T extends YourSuperType> ...