我想序列化一个包含静态嵌套的CustomClass对象作为其值的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。是否因为在不同的类下定义的嵌套类将具有不同的名称或版本?
该问题可能的解决方案是什么? 谢谢
“readObject(Object)”对不起,这是在这里键入演示代码的错误。请阅读它作为out.readObject() –
然后它意味着'Class A'本身没有找到而运行'Class B'。你可以在运行'Class B'之前检查类路径,或者通过使用SystemClassloader来运行程序本身来记录类路径。 – Praveen