gpt4 book ai didi

Java 自定义序列化

转载 作者:IT老高 更新时间:2023-10-28 20:21:24 25 4
gpt4 key购买 nike

我有一个对象,其中包含一些我想要序列化的不可序列化字段。它们来自一个我无法更改的单独 API,因此不能将它们设为可序列化。主要问题是 Location 类。它包含四个我需要的可以序列化的东西,都是整数。如何使用 read/writeObject 来创建可以执行以下操作的自定义序列化方法:

// writeObject:
List<Integer> loc = new ArrayList<Integer>();
loc.add(location.x);
loc.add(location.y);
loc.add(location.z);
loc.add(location.uid);
// ... serialization code

// readObject:
List<Integer> loc = deserialize(); // Replace with real deserialization
location = new Location(loc.get(0), loc.get(1), loc.get(2), loc.get(3));
// ... more code

我该怎么做?

最佳答案

Java 支持 Custom Serialization .阅读自定义默认协议(protocol)部分。

引用:

There is, however, a strange yet crafty solution. By using a built-in feature of the serialization mechanism, developers can enhance the normal process by providing two methods inside their class files. Those methods are:

  • private void writeObject(ObjectOutputStream out) throws IOException;
  • private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException;

在这种方法中,如果需要,您可以将其序列化为其他形式,例如您说明的位置的 ArrayList 或 JSON 或其他数据格式/方法,然后在 readObject() 上重新构建它

在您的示例中,您添加以下代码:



private void writeObject(ObjectOutputStream oos)
throws IOException {
// default serialization
oos.defaultWriteObject();
// write the object
List loc = new ArrayList();
loc.add(location.x);
loc.add(location.y);
loc.add(location.z);
loc.add(location.uid);
oos.writeObject(loc);
}

private void readObject(ObjectInputStream ois)
throws ClassNotFoundException, IOException {
// default deserialization
ois.defaultReadObject();
List loc = (List)ois.readObject(); // Replace with real deserialization
location = new Location(loc.get(0), loc.get(1), loc.get(2), loc.get(3));
// ... more code

}

关于Java 自定义序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7290777/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com