假設我有:有沒有比使用instanceof更好/更簡潔的方式來有條件地創建一個類型? 【JAVA]
public class FightingZone<MobileSuitso, Background> {
private MobileSuitCollection<MobileSuitso> msCollection;
private BackgroundInfo<Background> bgInfo;
public FightingZone(MobileSuitCollection<MobileSuitso> newCollection, BackgroundInfo<Background> newInfo) {
this.msCollection = newCollection;
this.bgInfo = newInfo;
}
...
...// inside a method
MobileSuitCollection temporaryCollection = new MobileSuitCollection<MobileSuitso>(); // /!\
}
的問題是MobileSuitCollection是一個接口,所以我不能實例化。例如,我可以這樣做:
MobileSuitCollection temporaryCollection = new GundamMeisterCollection<MobileSuitso>();
MobileSuitCollection temporaryCollection = new InnovatorCollection<MobileSuitso>();
MobileSuitCollection temporaryCollection = new CannonFolderCollection<MobileSuitso>();
等。然而,操控temporaryCollection
,我需要的是同一類型的一個通過參數傳遞給我的班。所以我想這樣做的:
if (msCollection instanceof GundamMeisterCollection) {
...
} else if (msCollection instanceof InnovatorCollection) {
...
} ...
我意識到這是可怕的。然而。有一個更好的方法嗎?是否可以保留對初始類型使用的類的引用,然後用那個實例化temporaryCollection
?
我正在研究使用反射來獲取類名並從那裏實例化它。假設這是可能的,它會不會使代碼更清潔?或者這仍然是首選方法? – 2010-06-29 21:22:28
如果您要使用反射,請使用類對象而不是類名稱。像這樣:'Class cl = collection.getClass(); Interface inst = cl.newInstance();' –
2010-06-30 03:37:58
反射應該是最後的手段。上述方法是面向對象的方法。 – Bozho 2010-06-30 05:27:05