2011-09-13 44 views
0

的情況下可能重複:
get type of a generic parameter in java with reflection的Java:獲得通用

您好我讀到這裏關於解決方案,以獲得泛型類型的實例。我認爲我的問題有點不同,所以爲了方便,我將其分解。 讓我們假設我有三類:

public class Car(){ 
    public int velocity; 
    public String name; 
    public Car(int velocity, String name){ 
     this.velocity = velocity; 
     this.name = name; 
    } 
} 

public class ColoredCar extends Car(){ 
    public String color; 
    //setters and getters for color, same Constructor.... 
} 
public class DrivenCar extends ColoredCar(){ 
    public Driver driver; 
    //setters and getters, same Constructor 
} 

現在我延伸,就像ArrayList的:

public class Cars<CAR extends Car> extends ArrayList<CAR>{ 

    public String[] getColors(){ 
     String[] ret = new String[this.size()]; 
     int count = 0; 
     for(CAR c: this){ 
      ret[count++] = c.getColor(); 
     } 
     return ret; 
    } 
    //some more..... 
} 

好吧,如果我需要創建延伸Cars,並在其構造,我已經他們知道一類CAR的10個對象,我有什麼可能?我知道我可以用速度和名字創建車對象,我已經擁有了。

編輯: 可以說,我在我的汽車的功能:

public CAR createCar(int velocity, String name){ 
    return (CAR)new Car(velocity, name); 
} 

,並在運行時汽車被定義爲汽車,我得到一個錯誤,因爲我不能投了汽車的DrivenCar ?

+0

什麼的可能性? –

+0

創建類型爲CAR的對象作爲通用對象傳遞 –

+2

在這種情況下,您的問題與所有有關執行「新T」(或等效)的問題相同,其中「T」是通用參數。答案是:你不能。 (至少,不是沒有'T'的實例。) –

回答

1

如果您在運行時詢問如何構造對象T,則可以始終傳入T.class,然後使用其newInstance()方法創建該類型的對象。如果你問的是如何用T對象列表初始化你的容器類,那麼...

你可以定義一個構造函數,它使用super來調用父構造函數並傳入項目(轉換爲集合,第一個),或者你可以定義你自己的構造函數,簡單地調用add方法來添加你的十輛車。但是,這是對繼承模式的嚴重濫用。

繼承不用於代碼重用。它用於變化(即相同接口的多種不同的可能實現)。對於代碼重用,遏制幾乎總是一個更好的範例。 I .: .:

class Cars<CAR> { 
    private List<CAR> cars = new ArrayList<CAR>(); 

    // ... 

    public Iterable<String> getColors() { 
     return Iterables.transform(cars, getCarToColorTransform()); 
    } 

    // Expose other methods of List<CAR>, but ONLY the ones you need. 
} 
+0

看起來像一個Adapter-Pattern。這正是我用Cars做的,但爲了方便起見,我在這裏發佈了它,就像我繼承了ArrayList一樣。 –