Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Although the Serializable interface in Java has no methods, no fields, it can achieve its function. How?

Although the java.io.Serializable interface public interface Serializable{} surprisingly doesn't contain any methods and fields in Java, the class that implements this interface is able to achieve the function of serialization and deserialization (the state of the object being serialized or deserialized). How can it achieve the function of serialization and deserialization without any methods or fields in Java?

like image 441
Bhavesh Avatar asked Nov 05 '11 02:11

Bhavesh


People also ask

How many methods does Serializable have if no method then what is the purpose of the Serializable interface?

Serializable interface has two methods, readResolve() and writeReplace() , which are used to read and write object in database.

What if Serializable class contains non Serializable fields?

The class will not be serialisable, unless the field is declared transient (which will prevent the field from being serialised, i.e. it will not be saved).

Is Serializable a functional interface?

Serializable is a bit of a unique interface in this regards, as there is nothing you actually need to implement. Without making this cast, the lambda will be considered unserializable, which does not make Kryo happy.

What is the use of Serializable interface in Java?

Serializable interface. Serializable is a marker interface (has no data member and method). It is used to “mark” java classes so that objects of these classes may get certain capability. Other examples of marker interfaces are:- Cloneable and Remote.


2 Answers

Some interfaces serve only as "markers" or "flags".

The UID and custom readers/writers are accessed via reflection.

Serializable is a marker, and the JRE/JVM may take action(s) based on its presence.

http://en.wikipedia.org/wiki/Marker_interface_pattern

like image 145
Dave Newton Avatar answered Oct 12 '22 01:10

Dave Newton


Serializable doesn't contain any method, it's the ObjectOutputStream and ObjectInputStream classes that can do that work, through the writeObject and readObject methods.

Serializable is just a marker interface, in other words it just puts a flag, without requiring any fields or methods.

like image 36
stivlo Avatar answered Oct 12 '22 01:10

stivlo