第一个代码:
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()?