假设我有:有没有比使用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