[英]Java - Get instances of abstract class by <class ? extends SuperClass> with parameters
如果標題含糊不清,請問。
請允許我詳細說明我的問題:
想象一下,我有一個名為“ Car”的類,它是一個抽象類。 現在,假設我有多個Car實例,例如Audi,Volvo,Ferrari等。
我想將這些實例存儲在枚舉類中,這樣我就可以輕松地通過枚舉檢索它們。 但是,問題在於,每個實例的構造函數中都有一個參數,因此我不能將其作為枚舉的最終屬性。 我需要獲取從.class創建的超類(帶有1個參數)的實例。
偽代碼
/* This is my super class */
public abstract class Car{
public Car(Object param){ }
}
/* This is my instance */
public class Volvo extends Car{
public Volvo(Object param){
super(param);
}
}
/* This is my other instance */
public class Ferrari extends Car{
public Ferrari(Object param){
super(param);
}
}
上面的代碼正確顯示了我制作的類。 好了,現在是枚舉類:
public enum CarType{
VOLVO(Volvo.class), FERRARI(Ferrari.class);
private Class<? extends Car> instance;
private CarType(Class<? extends Car> instance){
this.instance = instance;
}
/* This is what I tried, NOT working*/
public Car getCarInstance(Object param){
try{
return Car.class.getConstructor(instance).newInstance(param);
}catch(Exception e){
/* I didn't do bugmasking, but all the exceptions would
make this post look messy.*/
}
}
}
結果需要什么:如果我將調用'CarType.VOLVO.getCarInstance(“ My parameter value”); '它將與'new Volvo(“ my parameter value”);'相同。
提前致謝。
在getCarInstance更改行后,嘗試執行以下操作:
return instance.getConstructor(Object.class).newInstance(param);
您不需要Car.class
因為您已經在枚舉構造函數中指定了類型。 順便說一句,不要叫它實例 ,叫它type 。
開始了:
public Car getCarInstance(Object param) {
try {
return type.getConstructor(Object.class).newInstance(param);
} catch (ReflectiveOperationException e) {
throw new IllegalStateException(e);
}
}
第二件事(如您所見)是如何檢索正確的構造函數。 如果您想了解更多信息,請閱讀更多有關反射的信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.