我写了两个简单的Junit测试用例,一个用于序列化,另一个用于反序列化。当我同时运行两个测试用例时,反序列化工作并为我提供了正确的存储值输出20。但是,当我一一运行测试用例时(或者您可以启动一个程序并进行序列化,然后启动一个程序来反序列化),我得到了不同的哈希码和不同的存储值10。
public class SerializedSingletonClass implements Serializable{
/**
*
*/
private static final long serialVersionUID = 10L;
private int value = 10;
private static class SingletonHolder{
private static SerializedSingletonClass ref = new SerializedSingletonClass();
}
public static SerializedSingletonClass getObject() {
return SingletonHolder.ref;
}
public Object readResolve() {
return SingletonHolder.ref;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}
}
我的测试用例一次要运行一次(就像您开始序列化然后再次开始反序列化一样)
public void breakingSingleton_of_SerializedSingletonClass_with_serialization() throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream oos = new ObjectOutputStream(
new FileOutputStream(
"serialized.ser"));
SerializedSingletonClass ref = SerializedSingletonClass.getObject();
ref.setValue(20);
oos.writeObject(ref);
System.out.println(ref.hashCode());
oos.close();
}
反序列化测试用例
@Test
public void test() throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectInputStream ois = new ObjectInputStream(
new FileInputStream(
"serialized.ser"));
SerializedSingletonClass ref2 = (SerializedSingletonClass) ois.readObject();
ois.close();
System.out.println(ref2.hashCode());
System.out.println(ref2.getValue());
}
输出:我得到的哈希码和值分别为10。
问题:如何正确反序列化?