【发布时间】:2016-04-13 03:20:28
【问题描述】:
目前我有一个程序可以从文件中保存和加载“变量”类型的 ArrayList。但是,我希望能够从一个文件中保存和加载不同的对象(不同类的实例,例如“变量”、“函数”..等)。这是我现在拥有的代码:
public SaveState(){
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(new FileOutputStream("vars.stt"));
} catch (IOException e) {
e.printStackTrace();
}
ArrayList<Variables> vars = new ArrayList<>();
vars.add(new Variables("g", 5));
vars.add(new Variables("f", -3.12));
try {
out.writeObject(vars);
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public LoadState(){
ObjectInputStream in = null;
try {
in = new ObjectInputStream(new FileInputStream("vars.stt"));
} catch (IOException e) {
e.printStackTrace();
}
try {
//final Object o = in.readObject();
final ArrayList<Variables> vars = (ArrayList<Variables>) in.readObject();
System.out.println(vars.toString());
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
此代码仅允许我从文件中加载一种对象类型。有没有办法以这种方式保存/加载多种对象类型?
【问题讨论】:
-
你没有尝试为函数和变量创建一个基类并使用基类类型的数组列表吗?
-
@ImeshaSudasingha 老实说,我不确定我是否能够做到这一点,这需要我重构很多代码(数百行)。有没有其他解决方案。
-
不,您可以创建一些基类(例如“ProgramElement”),它们只是从中扩展变量和函数类。无需重构代码。
-
@ImeshaSudasingha 那么,如果我有“变量”、“函数”和“列表”类,我将如何从一个类中扩展所有 3 个类?
-
为什么不使用 Object 类作为“基类”。你可以使用多态性。
标签: java serialization arraylist