Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Serialization, writeObject(Object obj) why not writeObject(Serializable obj)

The method signature of ObjectOutputStream's write method is

public final void writeObject(Object obj) throws IOException

As obj should implements Serializable (know about markers). Why java developers do not write this method as

public final void writeObject(Serializable obj) throws IOException

is there any reason ?

like image 752
sailor Avatar asked Jun 17 '13 09:06

sailor


People also ask

What do you do if an object should not or does not need to be serialized?

If we want to serialize one object but do not want to serialize specific fields, then we can mark those fields as transient. All the static fields belong to the class instead of the object, and the serialization process serializes the object so static fields can not be serialized.

Are all Java objects serializable?

A Java object is serializable if its class or any of its superclasses implements either the java. io. Serializable interface or its subinterface, java.

What is wrong with Java serialization?

If your object has changed, more than just adding simple fields to the object, it is possible that Java cannot deserialize the object correctly even if the serialization ID has not changed. Suddenly, you cannot retrieve your data any longer, which is inherently bad.

How do you make an object serializable in Java?

If you want a class object to be serializable, all you need to do it implement the java. io. Serializable interface. Serializable in java is a marker interface and has no fields or methods to implement.


1 Answers

writeObject is defined in ObjectOutput interface and its API says The class that implements this interface defines how the object is written. It means that theoretically there may be implementations other than ObjectOutputStream which may be using other ways of serialization which do not require the object be Serializable.

like image 127
Evgeniy Dorofeev Avatar answered Nov 10 '22 12:11

Evgeniy Dorofeev