Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ObjectOutputStream.writeObject not take a Serializable?

Tags:

Why does ObjectOutputStream.writeObject(Object o) not take a Serializable? Why is it taking an Object?

like image 954
Rajesh Avatar asked Apr 11 '11 13:04

Rajesh


People also ask

Is ObjectOutputStream serialized?

The combination of the FileOutputStream and the ObjectOutputStream will allow Java object serialization to happen at the file level.

What are the requirements for a class that you want to serialize with ObjectOutputStream?

Classes that are eligible for serialization need to implement a special marker interface, Serializable. Both ObjectInputStream and ObjectOutputStream are high level classes that extend java. io. InputStream and java.

Why is Java object not Serializable?

In Java, a NotSerializableException exception is thrown when an instance of a class must implement the Serializable interface. The exception is thrown by either the serialization runtime, or by the instance of the class. The argument for the NotSerializableException is the name of the class.

What happens if I don't implement Serializable?

If our class does not implement Serializable interface, or if it is having a reference to a non- Serializable class, then the JVM will throw NotSerializableException . All transient and static fields do not get serialized.


1 Answers

This is because writeObject in ObjectOutputStream overrides the method in the ObjectOutput interface which does not require that the object be Serializable.

The ObjectOutput interface specifies methods that allow objects to be written to a stream or underlying storage, but this may be achieved by a process other than serialization. The ObjectOutputStream implements this functionality, but requires serializable objects. However, it cannot modify the signature of the interface that it implements.

like image 102
AndyT Avatar answered Oct 14 '22 09:10

AndyT