Java - Deserialization InvalidClassException (No valid constructor)

后端 未结 3 1514
长发绾君心
长发绾君心 2021-02-19 02:33

I\'m trying to serialize an object and then deserialize it after sending its data to a client program.

Here\'s an example of how the object\'s inheritance works. The obj

3条回答
  •  再見小時候
    2021-02-19 03:21

    I faced the same issue with Hazelcast's serialization, but solved it without resorting to an intermediary class, by using custom serialization. I added an empty no-arg constructor to the Animal class and implemented the Person class as follows:

    class Person extends Animal implements Serializable {
    
        private void writeObject(ObjectOutputStream o) throws IOException {
            o.writeObject(this.fieldA);
            o.writeObject(this.fieldB);
            o.writeObject(this.fieldC);
            ...
        }
    
        private void readObject(ObjectInputStream o) throws IOException, ClassNotFoundException {
            this.fieldA = (TypeOfA) o.readObject();
            this.fieldB = (TypeOfB) o.readObject();
            this.fieldC = (TypeOfC) o.readObject();
            ...
        }
    }
    

提交回复
热议问题