如何将两个Java序列化对象链接在一起?

前端之家收集整理的这篇文章主要介绍了如何将两个Java序列化对象链接在一起?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
有时(实际上很多,我们得到一个 Java的情况,其中两个对象指向同一个东西.现在,如果我们分开这些序列化,则序列化表单具有对象的单独副本是非常合适的,因为应该可以打开另一个对象.但是,如果我们现在反对他们,我们发现他们仍然分开.有没有办法把它们连在一起?

示例如下.

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()));
 }

}

解决方法

readResolve() method允许这个(当然,首先你必须定义你将如何决定哪些对象是“相同的”).但是更容易的是将两个对象序列化到同一个文件中 – ObjectOut / InputStream保存所有被序列化/反序列化的对象的记录,并且只会存储和返回对已经看到的对象的引用.
原文链接:https://www.f2er.com/java/126547.html

猜你在找的Java相关文章