读取和写入(序列化)不同类中的静态嵌套类对象

问题描述 投票:0回答:3

我想序列化一个 Map 对象,其中包含静态嵌套 CustomClass 对象作为其值。

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。是不是因为不同类下定义的同一个嵌套类会有不同的名称或版本?

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

java exception serialization
3个回答
0
投票

是不是因为不同类下定义的同一个内部类会有不同的名称或版本?

这是因为“不同类下定义相同的内部类”是一个矛盾的说法。它一样。这是一个不同的班级。

NB

static inner
是一个矛盾的术语


0
投票

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


0
投票

在你的

class B
中,我已替换为以下行,它对我来说效果很好。

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

另外,我无法在

readObject(Object)
中找到以 Object 作为参数的
ObjectInputStream
方法。

© www.soinside.com 2019 - 2024. All rights reserved.