简体   繁体   English

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

[英]How can I access a Java constructor in a generic way?

I have a static builder method for a class "Model" that takes a JSON string and returns an ArrayList of Models. 我有一个类“模型”的静态构建器方法,它接受一个JSON字符串并返回一个模型的ArrayList。 I would like it refer to the Model's constructer generically so that subclasses can inherit the builder method. 我希望它通常引用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;
    }
}

This is a simplified implementation of the class, the relevant line being 这是类的简化实现,相关的行是

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

I know this isn't possible, but I would like to write something that calls the constructor of whatever type T happens to be. 我知道这是不可能的,但我想写一些东西,调用T恰好是什么类型的构造函数。 I have tried to use this(), which obviously doesn't work because the method "build" is static and I've tried to use reflection to determine the class of T but have been at a loss to figure out how to get it to work. 我试图使用this(),这显然不起作用,因为方法“build”是静态的,我试图使用反射来确定T的类,但一直在想弄清楚如何得到它上班。 Any help is greatly appreciated. 任何帮助是极大的赞赏。

Thanks, 谢谢,

Roy 罗伊

The workaround for "dynamic instantiation" with generics is to pass a hint to the class or the method: 使用泛型的“动态实例化”的解决方法是将提示传递给类或方法:

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

I'm happy to provide more help/ideas but I'm not sure what you want to achieve with your technical solution. 我很乐意提供更多帮助/想法,但我不确定您希望通过技术解决方案实现什么目标

(Note: Example has some over-simplified Exception handling) (注意:示例有一些过度简化的异常处理)

The way it is written now, I can't see that the T type parameter in build() is of any use whatsoever. 现在写的方式,我看不出build()中的T类型参数是否有任何用处。 Can't you just drop it and use Model in its place? 难道你不能放弃它并使用Model代替它吗? If so, that would solve your construction problem. 如果是这样,那将解决您的施工问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM