Search code examples
javaexternalizable

Do I need explicit default constructor when implementing Externalizable?


I know that if class A implements Externalizable it should have no-arg constructor, but if class doesn't have any constructors (like my A class) java provides empty no-arg constructor for it. So why I have an error there? If I explicitly add no-arg constructor (public A() {}) to the A class everything will be ok.
Error:

Exception in thread "main" java.io.InvalidClassException: A; no valid constructor at java.base/java.io.ObjectStreamClass$ExceptionInfo.newInvalidClassException(ObjectStreamClass.java:159) at java.base/java.io.ObjectStreamClass.checkDeserialize(ObjectStreamClass.java:864) at java.base/java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2061) at java.base/java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1594) at java.base/java.io.ObjectInputStream.readObject(ObjectInputStream.java:430) at Test.main(Test.java:19)

import java.io.*;

public class Test implements Serializable
{
    public static void main(String[] args) throws IOException, ClassNotFoundException
    {

        // initiaizing
        A a1 = new A();

        // serializing
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(a1);
        oos.close();

        // deserializing
        ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(baos.toByteArray()));
        A a2 = (A) ois.readObject();
    }
}

class A implements Externalizable
{
    @Override
    public void writeExternal(ObjectOutput objectOutput) throws IOException {}

    @Override
    public void readExternal(ObjectInput objectInput) throws IOException, ClassNotFoundException {}
}

Solution

  • Externalizable requires a public no-args constructor, but provided no-arg constructor have default access modifier (also called package private) Try this: public class A() {}