首先代码:法提取,泛型,反射
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()?
难道不应该是“公告。类”? – 2012-08-07 13:06:00
'cls = Announcement.class'和'cls.getDeclaredConstructor(JSONObject.class)'得到Announcement的构造函数,它将JSONObject作为参数(除非我将其混合?)。 – assylias 2012-08-07 13:09:14
哦,等一下。你是对的!抱歉。这可能是最好的,如果你表明'cls'是Announcement.class – 2012-08-07 13:10:30