How do I link two Java serialized objects together?
•
Java
Sometimes (actually many), we get a Java case where two objects point to the same thing. Now, if we separate these serializations, it is very appropriate for the serialization form to have a separate copy of the object, because it should be possible to open another object. But if we oppose them now, we find that they are still separated. Is there a way to connect them together?
Examples are as follows
public class Example { private static class ContainerClass implements java.io.Serializable { private ReferencedClass obj; public ReferencedClass get() { return obj; } public void set(ReferencedClass obj) { this.obj = obj; } } private static class ReferencedClass implements java.io.Serializable { private int i = 0; public int get() { return i; } public void set(int i) { this.i = i; } } public static void main(String[] args) throws Exception { //Initialise the classes ContainerClass test1 = new ContainerClass(); ContainerClass test2 = new ContainerClass(); ReferencedClass ref = new ReferencedClass(); //Make both container class point to the same reference test1.set(ref); test2.set(ref); //This does what we expect: setting the integer in one (way of accessing the) referenced class sets it in the other one test1.get().set(1234); System.out.println(Integer.toString(test2.get().get())); //Now serialise the container classes java.io.ObjectOutputStream os = new java.io.ObjectOutputStream(new java.io.FileOutputStream("C:\\Users\\Public\\test1.ser")); os.writeObject(test1); os.close(); os = new java.io.ObjectOutputStream(new java.io.FileOutputStream("C:\\Users\\Public\\test2.ser")); os.writeObject(test2); os.close(); //And deserialise them java.io.ObjectInputStream is = new java.io.ObjectInputStream(new java.io.FileInputStream("C:\\Users\\Public\\test1.ser")); ContainerClass test3 = (ContainerClass)is.readObject(); is.close(); is = new java.io.ObjectInputStream(new java.io.FileInputStream("C:\\Users\\Public\\test2.ser")); ContainerClass test4 = (ContainerClass)is.readObject(); is.close(); //We expect the same thing as before,and would expect a result of 4321,but this doesn't happen as the referenced objects are Now separate instances test3.get().set(4321); System.out.println(Integer.toString(test4.get().get())); } }
Solution
The readresolve () method allows this (of course, first you must define how you will decide which objects are "the same") But it's easier to serialize two objects into the same file – objectout / InputStream keeps a record of all serialized / deserialized objects, and only stores and returns references to objects already seen
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码