2010-11-11 49 views
3

我有一個類「模型」的靜態生成器方法,它需要一個JSON字符串並返回一個模型的ArrayList。我希望它通常引用模型的構造器,以便子類可以繼承構建器方法。如何以通用方式訪問Java構造函數?

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(),這顯然不起作用,因爲方法「構建」是靜態的,我試圖使用反射來確定T的類,但一直在弄清楚如何得到它上班。任何幫助是極大的讚賞。

感謝,

羅伊

+0

你如何決定你需要什麼子?這個決定需要以某種方式制定和編寫。是基於jsonArray.get(i)的返回值的決定嗎? (無論如何,該方法會返回什麼?) – perp 2010-11-11 06:56:20

回答

0

現在寫入的方式,我看不到在建T形參數()是不得以任何用途。難道你不能放下它並在其位置使用模型?如果是這樣,那將解決您的施工問題。

+0

如果我稱之爲「new Model(json)」,那麼當我繼承它時,它會轉換爲Model的子類嗎?我現在就試試看看 – royvandewater 2010-11-11 06:43:46

+0

不,它不會。但是靜態build()無法知道要實例化的子類,所以需要一種不同的方法。 – perp 2010-11-11 06:49:08

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

我很高興能提供更多的幫助/想法,但我不知道你是什麼想用您的技術解決方案實現

(注:例如有一些過於簡單的異常處理)