Java自定义序列化 [英] Java Custom Serialization

查看:219
本文介绍了Java自定义序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have an object that contains a few unserializable fields that I want to serialize. They are from a separate API that I cannot change, so making them Serializable is not an option. The main problem is the Location class. It contains four things that can be serialized that I'd need, all ints. How can I use read/writeObject to create a custom serialization method that can do something like this:

// 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支持自定义序列化。阅读自定义默认协议部分。

Java supports Custom Serialization. Read the section Customize the Default Protocol.

引用:


有然而,这是一个奇怪而又狡猾的解决方案。通过使用序列化机制的内置
功能,开发人员可以通过在其类文件中提供两个方法来增强
正常过程。
这些方法是:


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

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 for您说明的位置或JSON或其他数据格式/方法,并在readObject()上重新构建它。

In this method, what you could do is serialize it into other forms if you need to such as the ArrayList for Location that you illustrated or JSON or other data format/method and reconstruct it back on readObject()

使用您的示例,您添加以下代码:

With your example, you add the following code:



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自定义序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆