IMO,序列化Enumeration
并没有多大意义。AnEnumeration
只是数据结构或其他业务逻辑之上的浮动视图。为了序列化,你最好坚持序列化后台接口。为了可视化我正在写的内容,我设置了一个小代码片段:
import java.io.*;
import java.util.*;
import javax.swing.tree.TreePath;
public class EnumTest {
public class MyEnumerator<T> {
// set holding data
List<T> data;
public MyEnumerator(List<T> data) {
this.data = data;
}
public List<T> getData() {
return data;
}
public Enumeration<T> enumerate() {
return new Enumeration<T>() {
transient int i = 0;
@Override
public boolean hasMoreElements() {
return i < data.size();
}
@Override
public T nextElement() {
return data.get(i++);
}
};
}
}
public EnumTest() throws Exception {
List<TreePath> TreePaths = Arrays.asList(new TreePath[] { new TreePath("3"), new TreePath("4"), new TreePath("5") });
MyEnumerator<TreePath> myEnum1 = new MyEnumerator<TreePath>(TreePaths);
print(myEnum1);
FileOutputStream fos = new FileOutputStream("test.out");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(myEnum1.getData());
oos.close();
fos.close();
System.out.println("* Serialization complete");
FileInputStream fis = new FileInputStream("test.out");
ObjectInputStream ois = new ObjectInputStream(fis);
@SuppressWarnings("unchecked")
List<TreePath> data = (List<TreePath>) ois.readObject();
MyEnumerator<TreePath> myEnum2 = new MyEnumerator<TreePath>(data);
print(myEnum2);
System.out.println("* Deserialization complete");
}
private void print(MyEnumerator<TreePath> myEnum1) {
Enumeration<TreePath> enm = myEnum1.enumerate();
while (enm.hasMoreElements()) {
System.out.println(enm.nextElement());
}
}
public static void main(String[] args) throws Exception {
new EnumTest();
}
}
这解决了Enumeration
通过持久化包含的数据并在之后重建包装类来序列化自身的主题MyEnumerator
。通过序列化/反序列化循环,您将获得一个不同的对象,但在语义上是相同的。