Search code examples
javaexceptionserialization

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


I want to serialize a Map<String, CustomClass> object which contains a static nested CustomClass object as its value.

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
        ....
    }

}

When I am trying to read the serialized Map object, it throws the ClassNotFoundException. Is it because the same nested class defined under a different class will have a different name or version?

What could be the possible solution for that problem?


Solution

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

    It is because 'same inner class defined under different class' is a contradiction in terms. It isn't the same. It is a different class.

    NB static inner is also a contradiction in terms.