我想序列化一个 Map
public class A{
static Map<String, CustomClass> map = new HashMap<>();
public static void main(String[] args) {
map.put("ABC", new CustomClass(1, 2L, "Hello"));
writeToFile();
}
private static void writeToFile() throws IOException, ClassNotFoundException {
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("file.ser"));
out.writeObject(map);
}
private static class CustomClass implements Serializable {
int x;
long y;
String z;
private static final long serialVersionUID = 87923834787L;
private CustomClass (int x, long y, String z) {
.....
}
}
}
public class B {
static Map<String, CustomClass> map = new HashMap<>();
public static void main( String[] args) {
readFromFile();
}
private static void readFromFile() throws IOException, ClassNotFoundException {
ObjectInputStream out = new ObjectInputStream(new FileInputStream("file.ser"));
map = out.readObject(); // ClassNotFoundException occured
}
private static class CustomClass implements Serializable {
int x;
long y;
String z;
private static final long serialVersionUID = 87923834787L;
private CustomClass (int x, long y, String z) {
.....
}
//some utility methods
....
}
}
当我尝试读取序列化的 Map 对象时,它抛出 ClassNotFoundException。是不是因为不同类下定义的同一个嵌套类会有不同的名称或版本?
该问题的可能解决方案是什么?
嵌套类全名包括封闭类名。 A 写入 A$CustomClass 并且 B 有 B$CustomClass
在你的
class B
中,我已替换为以下行,它对我来说效果很好。
map = (Map<String, CustomClass>) out.readObject();//Line no 19
另外,我无法在
readObject(Object)
中找到以 Object 作为参数的 ObjectInputStream
方法。