How does Java's serialization work and when it should be used instead of some other persistence technique?

前端 未结 9 1041
失恋的感觉
失恋的感觉 2020-11-30 20:54

I\'ve been lately trying to learn more and generally test Java\'s serialization for both work and personal projects and I must say that the more I know about it, the less I

9条回答
  •  感情败类
    2020-11-30 21:20

    How does Java's built-in serialization works?

    Whenever we want to serialize an object, we implement java.io.Serializable interface. The interface which does not have any methods to implement, even though we are implementing it to indicate something to compiler or JVM (known as Marker Interface). So if JVM sees a Class is Serializable it perform some pre-processing operation on those classes. The operation is, it adds the following two sample methods.

    private void writeObject(java.io.ObjectOutputStream stream)
                throws IOException {
            stream.writeObject(name); // object property
            stream.writeObject(address); // object property
        }
    
        private void readObject(java.io.ObjectInputStream stream)
                throws IOException, ClassNotFoundException {
            name = (String) stream.readObject(); // object property
            address = (String) stream.readObject();// object property
        }
    

    When it should be used instead of some other persistence technique?

    The built in Serialization is useful when sender and receiver both are Java. If you want to avoid the above kind of problems, we use XML or JSON with the help of frameworks.

提交回复
热议问题