2012-08-07 78 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> ...