【发布时间】:2014-02-03 21:40:29
【问题描述】:
我正在尝试使用XMLEncoder 序列化具有另一个 ArrayList 的类的 ArrayList。可以做到吗?
这是我的代码的 sn-p:
public class Model {
private ArrayList<Student> students;
private ArrayList<Module> modules;
//...
public void saveStudentsXML() throws IOException {
XMLEncoder encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("students.xml")));
encoder.writeObject(students);
encoder.close();
}
public void loadStudentsXML() throws IOException {
XMLDecoder decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream("students.xml")));
students=(ArrayList<Student>)decoder.readObject();
decoder.close();
}
//this works fine
public void saveModulesXML() throws IOException {
XMLEncoder encoder=new XMLEncoder(new BufferedOutputStream(new FileOutputStream("modules.xml")));
encoder.writeObject(modules);
encoder.close();
}
public void loadModulesXML() throws IOException {
XMLDecoder decoder=new XMLDecoder(new BufferedInputStream(new FileInputStream("modules.xml")));
modules=(ArrayList<Module>)decoder.readObject();
decoder.close();
}
//this does not
}
Module 类有另一个 Student 类的 ArrayList(每个模块都有一个注册学生列表),
private ArrayList<Student> enrolledStudents;
当我查看 XML 时,似乎没有任何关于注册学生 ArrayList 的信息。
编辑:我已经为所有实例变量创建了 setter 和 getter,除了注册的Students ArrayList。据我所知,您不能为 ArrayList 创建 setter 方法,对吗?还有其他方法可以让 XMLEncoder 对其进行编码吗?
【问题讨论】:
标签: java xml serialization arraylist