简体   繁体   English

如何在Java中序列化/反序列化引用?

[英]How to serialize/deserialize reference in Java?

I would like to have serializable reference, which works within single machine only. 我想拥有可序列化的参考,该参考只能在单台机器上使用。

Such sort of object, being set to reference and serialized, and then deserialized, should reference exactly the same object as it was before serialization. 设置为引用并序列化然后反序列化的此类对象应引用与序列化之前完全相同的对象。

Obvious solution I made: 我提出的明显解决方案:

public class ReferenceSerializable<T> implements Serializable {

   public static final DataFormat REFERENCE = new DataFormat("application/prs.reference");

   private static Int2ObjectOpenHashMap<WeakReference<Object>> map = new Int2ObjectOpenHashMap<>();

   private T referent;
   private int identity;

   public ReferenceSerializable(T referent) {
      this.referent = referent;
      identity = System.identityHashCode(referent);
      if( !map.containsKey(identity) ) {
         map.put(identity, new WeakReference<Object>(referent));
      }

   }

   private void writeObject(java.io.ObjectOutputStream out) throws IOException {
      out.writeInt(identity);
   }

   private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
      identity = in.readInt();
      referent = (T) map.get(identity).get();
      if( referent == null ) {
         throw new IllegalStateException("Object does not exist anymore, reference is obsolete");
      }
   }

}

Is it possible to implement other way? 是否可以实现其他方式?

I got the point and I think you cannot do it in Java. 我明白了,我想您不能用Java做到这一点。 Even if you make up a different solution (other than the one you offered) you will anyway end up with a variation of "Dictionary" solution. 即使您提出了一个不同的解决方案(不同于您提供的解决方案),您最终还是会得到“词典”解决方案的变体。 So, you will need to store your artificial keys (and objects in some storage) anyway, since in Java, after deserialization, the object is completely detached, if you know what I mean. 因此,无论如何,您都将需要存储人工密钥(和对象在某些存储中),因为在Java中,反序列化之后,如果您知道我的意思,则对象是完全分离的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM