我有一個類叫做Creator,它包含兩個實例字段。這些字段屬於父類A.在創建者的構造函數中,我想傳遞類A的子類,然後從傳入的類型創建兩個對象並將引用分配給這兩個字段。我該如何做這樣的事情?我不知道如何做出這個概括。如何通過傳遞對象類型來創建多個對象?
編輯:類創建者只有接受A或A本身的孩子的類型。所以不是其他任何一般類型。 AND A沒有一個無參數的構造
所以這樣的,這裏GeneralClassifier是A,沒有一個無參數的構造函數:
public class TwoLevelClassifier <T> {
private GeneralClassifier firstCl, secondCl;
//The passed type shall *only* be a GeneralClassifier or a child of it
public TwoLevelClassifier(GeneralClassifier cl) {
firstCl = //create a new classifier that is of the type passed to the constructor
secondCl = //create a new classifier that is of the type passed to the constructor
}
}
我不知道,但也許這功能在java中稱爲泛型?
你應該使用反射。看到這個:http://stackoverflow.com/questions/10470263/create-new-object-using-reflection – Massimo
爲什麼不使用泛型? 'public class Creator {' –
crush
是否需要將兒童類型的實例作爲ctor的參數傳遞?你沒有做任何事情,所以我不假設 – crush