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&开发者_开发问答gt;(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
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. Can't you just drop it and use Model in its place? If so, that would solve your construction problem.
精彩评论