I have a static build method for the Model class that takes a JSON string and returns an ArrayList of models. I would like it to refer to the Model constructor in the general case, so that subclasses can inherit the build method.
public class Model
{
protected int id;
public Model(String json) throws JSONException
{
JSONObject jsonObject = new JSONObject(json);
this.id = jsonObject.getInt("id");
}
public static <T extends Model> ArrayList<T> build(String json) throws JSONException
{
JSONArray jsonArray = new JSONArray(json);
ArrayList<T> models = new ArrayList<T>(jsonArray.length());
for(int i = 0; i < jsonArray.length(); i++)
models.add( new T(jsonArray.get(i)) )
return models;
}
}
This is a simplified implementation of the class, and the corresponding line is
models.add( new T(jsonArray.get(i)) )
I know this is not possible, but I would like to write something that calls a constructor of any type T. I tried using this (), which obviously does not work, because the "build" method is static, and I tried using reflection to determine the class T, but was in difficulty to figure out how to get it working. Any help is appreciated.
Thank,
Roy