的情況下可能重複:
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 ?
什麼的可能性? –
創建類型爲CAR的對象作爲通用對象傳遞 –
在這種情況下,您的問題與所有有關執行「新T」(或等效)的問題相同,其中「T」是通用參數。答案是:你不能。 (至少,不是沒有'T'的實例。) –