First code:
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();
}
Second:
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();
}
I am thinking about extracting a method which will cover these two codes. I think the method should look more or less like this:
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;
}
So later instead of first code I can just call Bond[] bonds = (Bond[]) getObjectsArray(jsonArray, Bond).
This is the most problematic line:
objects[i] = new Announcement(json); // FIXME: How to pass "json" arg to the constructor with cls.newInstance()?
You can use the following syntax to use a constructor with arguments (I assume the argument of the constructor is a
JSONObjectand that the constructor is public – if it is not, use thegetDeclaredConstructormethod):