我想序列化一個包含靜態嵌套的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