如何以通用方式访问Java构造函数?

时间:2010-11-11 06:32:35

标签: java inheritance constructor generics parameterized

我有一个类“Model”的静态构建器方法,它接受一个JSON字符串并返回一个ModelList的ArrayList。我希望它通常引用Model的构造函数,以便子类可以继承构建器方法。

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;
    }
}

这是该类的简化实现,相关的行是

models.add( new T(jsonArray.get(i)) )

我知道这是不可能的,但是我想写一些东西来调用T恰好是什么类型的构造函数。我试图使用this(),这显然不起作用,因为方法“build”是静态的,我试图使用反射来确定T的类,但一直在想弄清楚如何得到它上班。非常感谢任何帮助。

谢谢,

罗伊

2 个答案:

答案 0 :(得分:1)

使用泛型的“动态实例化”的解决方法是将提示传递给类或方法:

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 :(得分:0)

现在编写它的方式,我看不出build()中的T类型参数有任何用处。难道你不能放弃它并使用Model代替它吗?如果是这样,那将解决您的施工问题。