Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you make an object serializable at runtime?

Just like the title says, is there a way to check if an object is serializable, and if not, make it so at run time?

like image 791
Chad Cook Avatar asked Sep 07 '10 16:09

Chad Cook


People also ask

How an object can become a serializable?

To serialize an object means to convert its state to a byte stream so way that the byte stream can be reverted back into a copy of the object. 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 system runtime serialization?

Contains classes that can be used for serializing and deserializing objects. Serialization is the process of converting an object or a graph of objects into a linear sequence of bytes for either storage or transmission to another location.

What happens if object is not serialized?

What happens if you try to send non-serialized Object over network? When traversing a graph, an object may be encountered that does not support the Serializable interface. In this case the NotSerializableException will be thrown and will identify the class of the non-serializable object.

Can we serialize an object without implementing serializable interface?

If the superclass is Serializable, then by default, every subclass is serializable. Hence, even though subclass doesn't implement Serializable interface( and if its superclass implements Serializable), then we can serialize subclass object.

Can we serialize every object in Java?

A Java object is serializable if and only if its class or any of its parent classes implement either the java. io. Serializable interface or its subinterface, java.


1 Answers

Short answer - no.

Longer answer - yes, using byte-code manipulation, for example with asm. But you should really consider whether this is needed. Serialization is a serious matter (Effective Java has a whole chapter on serialization)

Btw, there are alternatives to binary serialization, that do not require the object implementing Serializble (as pointed by Jacob in the comments):

  • XML - java.beans.XMLEncoder.encode(..) is the xml version of ObjectOutputStream
  • JSON - frameworks like Jacskon, Gson let you serialize an object with one line.
like image 156
Bozho Avatar answered Sep 30 '22 05:09

Bozho