如何以通用方式访问 Java 构造函数?
我有一个用于类“Model”的静态构建器方法,它接受 JSON 字符串并返回模型的 ArrayList。我希望它一般地引用模型的构造函数,以便子类可以继承构建器方法。
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 的类,但一直不知道如何获取它去工作。非常感谢任何帮助。
谢谢,
罗伊
I have a static builder method for a class "Model" that takes a JSON string and returns an ArrayList of Models. I would like it refer to the Model's constructer generically so that subclasses can inherit the builder 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, 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. 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. Any help is greatly appreciated.
Thanks,
Roy
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用泛型进行“动态实例化”的解决方法是向类或方法传递提示:
我很乐意提供更多帮助/想法,但我不确定您想要实现什么目标实现您的技术解决方案。
(注意:示例有一些过于简化的异常处理)
The workaround for "dynamic instantiation" with generics is to pass a hint to the class or the method:
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)
按照现在的写法,我看不出build()中的T类型参数有任何用处。难道你不能放弃它并使用 Model 来代替它吗?如果是这样,那就可以解决您的施工问题。
The way it is written now, I can't see that the T type parameter in build() is of any use whatsoever. Can't you just drop it and use Model in its place? If so, that would solve your construction problem.