0
votes
import java.io.*;

public class StaticVariableTest {
    public static void main(String[] args) throws IOException, ClassNotFoundException {
        AC AC = new AC();
        AC.b = 25;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(AC);
        oos.flush();
        oos.close();
        bos.close();

        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        AC na = (AC) ois.readObject();

        System.out.println(na.b);


    }
}

class AC implements Externalizable {
    private static final long serialVersionUID = 1L;
    int b = 20;

    @Override
    public void writeExternal(ObjectOutput objectOutput) throws IOException {
    }

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

Why in the above program I am getting InvalidClassException?

Exception in thread "main" java.io.InvalidClassException: serializationExamples.AC; 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 serializationExamples.StaticVariableTest.main(StaticVariableTest.java:18)

It says no valid constructor but a default no-arg constructor should have been provided by java for class A.

1

1 Answers

4
votes

From the Javadoc:

When an Externalizable object is reconstructed, an instance is created using the public no-arg constructor

You don't have a public no-arg constructor, because the class isn't public.

From JLS 8.8.9 Default Constructor:

The default constructor has the same access modifier as the class, unless the class lacks an access modifier, in which case the default constructor has package access (ยง6.6).