在不同的 classes 中读写(序列化)静态嵌套 class 对象

Reading and Writing (Serializing) static nested class object in different classes

我想序列化一个包含静态嵌套 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。是不是因为在不同class下定义的同一个嵌套class会有不同的名称或版本?

该问题的可能解决方案是什么。 谢谢

嵌套 class 全名包括封闭的 class 姓名。 A 写入 A$CustomClass 并且 B 有 B$CustomClass

Is it because the same inner class defined under different class will have different name or version?

因为'same inner class defined under different class'是个自相矛盾的词。 不一样。这是不同的 class.

注意 static inner is also a contradiction in terms.

在你的 class B 中,我已经替换为下面的行,它对我来说工作正常。

 map = (Map<String, CustomClass>) out.readObject();//Line no 19

此外,我无法在 ObjectInputStream 中找到 readObject(Object) 以 Object 作为参数的方法。