2

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 {}
}
Denys_newbie
  • 1,140
  • 5
  • 15

1 Answers1

1

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() {}

Denys_newbie
  • 1,140
  • 5
  • 15
DwB
  • 37,124
  • 11
  • 56
  • 82
  • whether java provides not public no-arg constructor if other not provided? – Denys_newbie Jan 20 '21 at 15:50
  • 1
    The class must be public. The no-arg constructor will be provided as normal. – DwB Jan 20 '21 at 16:04
  • 1
    a public constructor does not make a package access class magically turn into a public class. The ability to call the constructor is a requirement, but access to the class is an implied requirement as well. – DwB Jan 20 '21 at 16:05