Why standard serialization is not allowed in the enum class

I searched the web to find answers to some of the queries related to the enum class in java.

My query is why the default de-serialization was prevented in the enum class. I see that the enum class implements the Serializable interface, but it also has two methods, as shown below:

 private void readObject(ObjectInputStream in) throws IOException,
    ClassNotFoundException {
    throw new InvalidObjectException("can't deserialize enum");
}

private void readObjectNoData() throws ObjectStreamException {
    throw new InvalidObjectException("can't deserialize enum");
}

I am more embarrassed to see this class. Any help would be appreciated. Thanks in advance.

I'm more confused since ENUM implements a serializable interface and has the methods described above that throw "throw new InvalidObjectException" ("can deserialize enum"); An exception. so I don’t understand what is above two methods?

Also, the comments above the two methods say "prevent default deserialization", what does this mean?

+4
2

- Serializable.

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class Dummy {

    public enum Color {
        RED, GREEN, BLUE
    }

    public static void main(String[] args) throws Exception {

        System.out.println(deserialize(serialize(Color.GREEN), Color.class));
    }

    private static <T> T deserialize(byte[] data, Class<T> cls) throws IOException, ClassNotFoundException {

        try (final ByteArrayInputStream stream = new ByteArrayInputStream(data);
             final ObjectInputStream reader = new ObjectInputStream(stream)) {

            return cls.cast(reader.readObject());
        }
    }

    private static byte[] serialize(Serializable obj) throws IOException {

        final ByteArrayOutputStream stream = new ByteArrayOutputStream();

        try {

            try (final ObjectOutputStream writer = new ObjectOutputStream(stream)) {

                writer.writeObject(obj);
            }

        } finally {

            stream.close();
        }

        return stream.toByteArray();
    }
}

- , , , .

" " / , singleton. readObject - , , , .

TL; DR () , , Enum Serializable. VM/run-time .

+4

, Java enum JVM, deserialize() , , singleton-.

+2

Source: https://habr.com/ru/post/1622719/


All Articles