The basics of serialization in Java are not understood

I cannot understand the basics of Serialization in Java 1.6.

The following is the Dog class containing the instance variable Collar Class:

Dog.java

 public class Dog implements Serializable { private Collar collar; public Collar getCollar() { return collar; } public void setCollar(Collar collar) { this.collar = collar; } } 

The Collar class does not implement the Serializable interface, as shown below:

Collar.java

 public class Collar { private int size; public int getSize() { return size; } public void setSize(int size) { this.size = size; } } 

Now when I try to serialize Dog , why doesn't it throw a NotSerializableException ? Under the contract, the whole graphic object should implement Serializable , but my Collar class does not do this.

The following is the main method for this demo:

 public static void main(String[] args) { try { FileOutputStream fs = new FileOutputStream("E:\\test.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); Dog dog = new Dog(); // No exception thrown here, WHY? // test.ser file is getting created properly. os.writeObject(dog); FileInputStream fis = new FileInputStream("E:\\test.ser"); ObjectInputStream ois = new ObjectInputStream(fis); Dog dog1 = (Dog)ois.readObject(); // Here I am getting a null Collar object Collar c1 = dog1.getCollar(); 

Please explain this, I'm completely confused, trying to implement all the theoretical materials :(

+4
source share
2 answers

It seems that you have a misunderstanding of the concept of a graph of objects. In this graph, the nodes are instances (not classes), and the edges are formed from the values ​​of the instance variables specific to the reference type.

For your example

 Dog dog = new Dog(); 

creates an object graph consisting of a single instance of node, Dog . The collar variable is null , so its value does not form edges without another node. But if you add a line like

 dog.setCollar(new Collar()); 

your graphic now contains two nodes connected by the edge formed by the value in the collar instance variable.

Now all this in relation to serialization means that your published example serializes a one-node object graph, all nodes of which are serializable, but if you add a collar, this graph will contain a non-serializable node and you will get the exception that you expect.

+2
source

Maybe because your dog does not have collar !

Try

 Dog dog = new Dog(); dog.setCollar(new Collar()); 
+9
source

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


All Articles