我有抽象类A的不同子类,它们都应该实现一个getInstance方法。该方法检查实例是否已以xml格式(XStream library)保存在光盘上并加载它或创建新实例。
public MySubclassB extends A {
...
private static SettingsManager<MySubclassB> manager;
private static MySubclassB instance;
private MySubclassB() {
manager = new SettingsManager<MySubclassB>();
}
public static MySubclassB getInstance() {
if (instance == null) {
MySubclassB tmp = new MySubclassB();
// loadObject returns either tmp if no instance was saved on disc or the saved object
if ((instance = manager.loadObject(tmp, MySubclassB.class.getCanonicalName())).hashCode() == tmp.hashCode()) {
setUpObjectFirstTime();
}
}
return instance;
}
}
是否可以在抽象类A中完成所有这些操作,还是应该复制所有子类中的代码?
答案 0 :(得分:0)
您必须复制代码,因为类型参数仅与实例相关,因此无法在静态字段或方法中使用。
https://docs.oracle.com/javase/tutorial/java/generics/restrictions.html#createStatic