第一个代码:
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[] bond = (Bond[]) getObjectsArray(jsonArray, Bond),而不是第一个代码
。
这是最有问题的一行:
objects[i] = new Announcement(json); // FIXME: How to pass "json" arg to the constructor with cls.newInstance()?
最佳答案
您可以使用以下语法来使用带参数的构造函数(我假设构造函数的参数是 JSONObject
并且构造函数是公共(public)的 - 如果不是,请使用 getDeclaredConstructor
方法):
Class<Announcement> cls = Announcement.class; //the second argument of your method
objects[i] = cls.getConstructor(JSONObject.class).newInstance(json);
关于java - 方法提取、泛型、反射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11846577/