假设我有:
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
?