java - java中反序列化步骤

标签 java serialization

 class A extends Serializable{
      public A(){}
int x=0;
      private final transient ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    }

关于反序列化的几个问题: 1)为什么案例序列化时需要提供默认构造函数? 2) 为什么反序列化后字段“lock”没有被初始化?

编辑:忘记在我原来的帖子中添加“ transient ”。现在添加它。

最佳答案

  1. 不需要
  2. 锁被初始化,下面的代码确实打印了初始化的锁(只需将 B 的对象写入字节数组并从中读取)

    public class B implements Serializable {
        private int x = 0;
        private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    
        public static void main(String[] args) throws IOException, ClassNotFoundException {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            try (ObjectOutput out = new ObjectOutputStream(bos)) {
                 out.writeObject(new B());
            }
            catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
            byte[] bytes = bos.toByteArray();
    
            ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
            try (ObjectInput in = new ObjectInputStream(bis)) {
                B b = (B) in.readObject();
                System.out.println(b.lock);
            }
            catch (IOException e) {
                e.printStackTrace();
                throw e;
            }
          }
       }
    }
    

关于java - java中反序列化步骤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30208552/

相关文章:

java - 安卓穿戴: how to store data in WearableListenerService and access them?

java - 在 JavaScript 中解析来自 Java Jackson JSON 的 JSON

java - java序列化问题

java - 如何在java中序列化OBJECT ARRAY?

java - 在 paint() 中调用 repaint() 会导致无限递归吗?

java - JAX-B : Missing XML attributes on child elements

java - Admob 广告无法加载

c# - 使用 DataContractSerializer(typeof(BaseClass)) 反序列化继承类

c# - Visual Studio的 "Add Service Reference"是如何反序列化对象的?

json - 使用 DispatchQueue Swift 迭代 JSONSerialization 中的不同链接