2014-12-04 28 views
1

動態類型的數組列表我有什麼是超一流的生成Java

class Geometry{ 
} 

和兩個類,擴展它:

class ShapeOne extends Geometry{} 

class ShapeTwo extends Geometry{} 

我想要實現的是生成一個列表(從數據庫中讀取)類型爲ShapeOneShapeTwo的對象或任何其他爲Geometry的實例的對象,但動態傳遞類型作爲參數,例如 ,例如:

public ArrayList< Geometry Object > getList(/**passing typeof generated list**/){ 
    // getting data from Database; 
    return new ArrayList<typeof generated list>(); 
} 

so the call would be then like: 
getList(ShapeTwo); 

感謝您的幫助:)

回答

3

你可以通過Class<T>,這樣做:

public <T extends GeometryObject> List<T> getList(Class<T> itemClass) throws Exception { 
    List<T> res = new ArrayList<T>(); 
    for (int i = 0 ; i != 10 ; i++) { 
     res.add(itemClass.newInstance()); 
    } 
    return res; 
} 

Demo.

注:以newInstance上面的調用假定類有一個參數的構造函數。

+0

好的,比我的類應該有一個靜態的newInstance(),對吧? – user1908375 2014-12-04 19:50:29

+0

@ user1908375'類'已經提供['的newInstance()'](http://docs.oracle.com/javase/6/docs/api/java/lang/Class.html#newInstance%28%29)方法。你確實需要一個無參數的構造函數才能工作。 – dasblinkenlight 2014-12-04 19:52:25

+0

...只有當類具有公共默認(無參數)構造函數時。 – mike 2014-12-04 19:53:13

3

你不能做到這一點。由於type erasure,List<Geometry>不是List<ShapeOne>的超級類別。這裏最好解釋一下:Is List<Dog> a subclass of List<Animal>? Why aren't Java's generics implicitly polymorphic?

一些替代品來解決問題:

  • 返回List<ShapeOne>List<ShapeTwo>List<TheExpectedClass>而非List<Geometry>
  • 返回<T extends Geometry> List<T>並通過Class<T> clazz作爲參數。可能需要使用附加參數來識別從數據庫中恢復的數據是否屬於Geometry的特定子類。
+0

謝謝,我會盡力做到這一點。 – user1908375 2014-12-04 19:46:36