How can I access the Java constructor in general?

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

+3
2

" " - :

public class Model<T> {
  Class<T> hint;
  public Model(Class<T> hint) {this.hint = hint;}

  public T getObjectAsGenericType(Object input, Class<T> hint) throws Exception {
    return hint.cast(input);
  }

  public T createInstanceOfGenericType(Class<T> hint) throws Exception {
    T result = hint.newInstance();
    result.setValue(/* your JSON object here */);
    return result;
  }
}

/, , .

(. )

+1

, , , T build() . ? , .

0

Source: https://habr.com/ru/post/1774231/


All Articles