Java中需要序列化

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2475448/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:10:50  来源:igfitidea点击:

Need of serialization in Java

java

提问by JavaUser

Can anyone tell me what is the need of Serialization in Java and give me an example scenario to explain the need? (I already understand what serialization is, I just want to understand when you'd use it).

谁能告诉我在 Java 中需要什么序列化并给我一个示例场景来解释需求?(我已经了解什么是序列化,我只是想了解您何时使用它)。

采纳答案by Vaishak Suresh

Serialization is usually used When the need arises to send your data over network or stored in files. By data I mean objects and not text.

当需要通过网络发送数据或存储在文件中时,通常使用序列化。我所说的数据是指对象而不是文本。

Now the problem is your Network infrastructure and your Hard disk are hardware components that understand bits and bytes but not JAVA objects.

现在的问题是您的网络基础设施和您的硬盘是理解位和字节而不是 JAVA 对象的硬件组件。

Serialization is the translation of your Java object's values/states to bytes to send it over network or save it.

序列化是将 Java 对象的值/状态转换为字节以通过网络发送或保存它。

This is analogous to how your voice is transmitted over PSTN telephone lines.

这类似于您的语音如何通过 PSTN 电话线传输。

回答by Thilo

When you want to save an object's state into a file or send it over the network, you need to transform it into a series of bytes. This is called serialization.

当您想将对象的状态保存到文件中或通过网络发送时,您需要将其转换为一系列字节。这称为序列化。

Java has a built-in mechanism for that, other options include XML or JSON.

Java 有一个内置的机制,其他选项包括 XML 或 JSON。

Examples when you need this: Caching objects, making remote method calls, saving an object graph to disk.

您需要的示例:缓存对象、进行远程方法调用、将对象图保存到磁盘。

回答by lajuette

  • If you want to store an object (-structure) on disk you'll need serialization.
  • A webservice requires serialization of objects to xml before they can be transmitted.
  • 如果你想在磁盘上存储一个对象(-structure),你需要序列化。
  • Web 服务需要将对象序列化为 xml,然后才能传输它们。

回答by Michael Aaron Safyan

Java serialization (and, specifically, the Serializableand Exernalizableinterfaces) allows you to read/write arbitrarily complicated Java objects, automatically or manually from/to disk or from/to the network. Whereas XML and JSON are textual formats, Java serialization is a binary format. (Serialization is also a general concept of simply reading/writing data, but since the question is about Java, I assume you are referring to the builtin serialization system, i.e. Serializable/Exernalizable)

Java 序列化(特别是SerializableExernalizable接口)允许您自动或手动从/向磁盘或从/向网络读取/写入任意复杂的 Java 对象。XML 和 JSON 是文本格式,而 Java 序列化是二进制格式。(序列化也是简单读/写数据的一般概念,但由于问题是关于 Java 的,我假设您指的是内置序列化系统,即 Serializable/Exernalizable)

Advantages of "implements Serializable" over XML/JSON
At first, you get serialization pretty much for free. You don't need to make very many changes to your objects in order to let the serialization mechanism work with it. Another advantage is that, because it is a binary format, it is much more compact than the textual format, and so will probably use less space (which is good for conserving network bandwidth or for conserving storage space on disk).

“实现可序列化”相对于 XML/JSON 的优势
首先,您可以免费获得序列化。您无需对对象进行太多更改即可让序列化机制使用它。另一个优点是,因为它是一种二进制格式,它比文本格式更紧凑,因此可能使用更少的空间(这有利于节省网络带宽或节省磁盘上的存储空间)。

Disadvantages "implements Serializable" over XML/JSON
The disadvantage to builtin Java serialization is that, if you make changes to your object, making the different serialization formats compatible can really be a major nightmare. Also, whereas you can manually edit XML and JSON, you cannot edit a serialized Java object (without reading it into Java). For the same reasons, it is often easier to debug XML and JSON than binary formats, because XML and JSON are human-readable. Another disadvantage with Java's builtin serialization mechanism is that you cannot (easily) serialize/deserialize the data from another programming language.

与 XML/JSON
相比,“实现可序列化”的缺点 内置 Java 序列化的缺点是,如果您对对象进行更改,则使不同的序列化格式兼容真的是一场噩梦。此外,虽然您可以手动编辑 XML 和 JSON,但您不能编辑序列化的 Java 对象(不将其读入 Java)。出于同样的原因,调试 XML 和 JSON 通常比二进制格式更容易,因为 XML 和 JSON 是人类可读的。Java 内置序列化机制的另一个缺点是您不能(轻松)序列化/反序列化来自另一种编程语言的数据。

Alternative techniques for reading/writing data
There are alternative serialization techniques other than Java's builtin serialization that give you the best of both worlds: compact binary formats, language interoperation, ease of version compatibility, and often debugging tools as well that make it easy to dump the binary data in readable format. For example, Google's opensource protocol buffersand MessagePackare examples of serialization libraries/formats that let you read/write compact binary data and easily maintain version compatibility. The biggest downside of these libraries over builtin Java serialization is that they involve plain-old-data objects for serialization (as opposed to more fully-featured Java objects that also have behavior associated with them); however, this disadvantage is, in fact, an advantage as separating the data model to which/from which the information is stored from the objects that wrap or are derived from them is actually a good programming practice and makes it easier to support multiple formats.

读取/写入数据
的替代技术除了 Java 的内置序列化之外,还有其他序列化技术可以为您提供两全其美的优势:紧凑的二进制格式、语言互操作、易于版本兼容性以及经常调试工具,可以轻松转储可读格式的二进制数据。例如,Google 的开源协议缓冲区MessagePack是序列化库/格式的示例,可让您读/写紧凑的二进制数据并轻松维护版本兼容性。与内置 Java 序列化相比,这些库的最大缺点是它们涉及用于序列化的纯旧数据对象(而不是功能更齐全的 Java 对象,这些对象也具有与其相关联的行为);然而,这个缺点实际上是一个优点,因为将存储信息的数据模型与包装或派生自它们的对象分开实际上是一个很好的编程实践,并且更容易支持多种格式。

Usage
Since you asked for the need, not merely the definition, there are a number of use cases:

用法
既然您要求的是需求,而不仅仅是定义,那么有许多用例:

  1. Simply saving your data for use later. For example, let's say you are writing a video game. Your program will not run forever; even if it never crashes (which is hopefully the case), your user will probably exit the program at some point or the operating system may kill the program to save resources (e.g. on Android, background processes that the user is not interacting with are frequently and intentionally killed by the OS to reclaim system resources like RAM). In order to ensure that the user doesn't start from the very beginning and can instead resume from where they were or from the most recent save point, you will want to write the state of the game to persistent storage (i.e. the hard drive, the user's Google Drive account, etc.). In order to do this, you need to translate the data structures in memory that represent the state of the game to raw bytes that you can write to disk (or to whatever system you are saving the data).

  2. Retrieving information from a remote server. Let's continue with the game example... suppose you are creating an online multiplayer game or that you want to make it possible to provide new levels or items in the game without the user updating their app. To do this, you would want the information about the online player or the information about the new levels/items to be communicated from a server computer (which you use as the point of contact for all the copies of the app installed on various devices) to the individual copies of the app. Both the server and app need some sort of in-memory representation of these data structures (e.g. the location of other players, the structure of a new level, the description/image for a new item, etc.), but to transfer the information from the server to the app on the device, the communication system consists of raw bytes, and so it is necessary to have a way to convert the data to raw bytes and from raw bytes back to a meaningful in-memory data structure.

  1. 只需保存您的数据以备后用。例如,假设您正在编写一个视频游戏。你的程序不会永远运行;即使它永远不会崩溃(希望是这种情况),您的用户可能会在某个时候退出程序,或者操作系统可能会终止程序以节省资源(例如,在 Android 上,用户不与之交互的后台进程频繁并被操作系统故意杀死以回收系统资源(如 RAM))。为了确保用户不会从头开始,而是可以从他们所在的位置或最近的保存点恢复,您需要将游戏状态写入持久存储(即硬盘驱动器,用户的 Google Drive 帐户等)。为此,

  2. 从远程服务器检索信息。让我们继续游戏示例...假设您正在创建一个在线多人游戏,或者您希望在用户不更新他们的应用程序的情况下在游戏中提供新的关卡或物品成为可能。为此,您需要从服务器计算机(您将其用作安装在各种设备上的所有应用程序副本的联系点)传送有关在线玩家的信息或有关新关卡/项目的信息到应用程序的各个副本。服务器和应用程序都需要这些数据结构的某种内存表示(例如其他玩家的位置、新关卡的结构、新项目的描述/图像等),但为了传输信息从服务器到设备上的应用程序,

Pretty much any communication between two different processes/apps or between an app and some storage system is a case where some sort of serialization mechanism is required.

几乎任何两个不同进程/应用程序之间或应用程序与某个存储系统之间的通信都是需要某种序列化机制的情况。

回答by Amit Kumar Gupta

Short story about serialization

关于连载的小故事

After many years of hard work, Earth's scientists developed a robot who can help them in daily work. But this robot had fewer features than the robots developed by the scientists from planet Mars.

经过多年的努力,地球的科学家们开发出了一种可以帮助他们进行日常工作的机器人。但是这个机器人的功能比火星科学家开发的机器人要少。

After a meeting between both planets' scientists, it is decided that Mars will send their robots to Earth. But a problem occurred. The cost of sending 100 robots to Earth was $100 million. And it takes around 60 days of traveling.

在两颗行星的科学家会面后,决定火星将他们的机器人送到地球。但是出现了问题。向地球发送 100 个机器人的成本为 1 亿美元。大约需要 60 天的旅行时间。

Finally, Mars' scientists decided to share their secret with Earth's scientists. This secret was about the structure of class/robot. Earth's scientists developed the same structure on Earth itself. Mars' scientists serializedthe data of each robot and sent it to earth. Earth's scientists deserializedthe data and fed it into each robot accordingly.

最后,火星科学家决定与地球科学家分享他们的秘密。这个秘密是关于类/机器人的结构。地球科学家在地球本身上开发了相同的结构。火星的科学家每个机器人的数据序列化并发送给地球。地球科学家数据反序列化并相应地将其输入每个机器人。

This process saved them time in communicating a massive amount of data.

这个过程为他们节省了大量数据通信的时间。

Some of the robots were being used in some defensive work on Mars. So their scientists marked some crucial properties of those robots as transientbefore sending their data to Earth. Note that the transient property is set to null (in case of reference) or to the default value (in case of the primitive type) when the object gets deserialized.

一些机器人被用于火星上的一些防御工作。因此,他们的科学家在将数据发送到地球之前,将这些机器人的一些关键特性标记为瞬态。请注意,当对象被反序列化时,transient 属性设置为 null(在引用的情况下)或默认值(在原始类型的情况下)。

One more point noticed by Earth's scientists is that Mars' scientists asked them to create some static variablesto keep details about the environment. These details are used by some robots. But Mars' scientists don't share these details. Because Earth's environment was different from Mars' environment.

地球科学家注意到的另一点是,火星的科学家要求他们创建一些静态变量来保留有关环境的详细信息。这些细节被一些机器人使用。但火星的科学家不会分享这些细节。因为地球的环境与火星的环境不同。

Even though knowing about the robot class structure and having serialized data Earth's scientist were not able to deserialize the data which can make robots working.

即使了解机器人类结构并序列化数据,地球科学家也无法反序列化可以使机器人工作的数据。

Exception in thread "main" java.io.InvalidClassException:
SerializeMe; local class incompatible: stream classdesc
:

Mars' scientists were waiting for the complete payment. Once the payment was done Mars' scientists shared the serialversionUID with Earth's scientists. Earth's scientist set it to robot class and everything started working.

火星的科学家们正在等待全额付款。付款完成后,火星的科学家与地球的科学家共享了 serialversionUID。地球科学家将其设置为机器人课程,一切都开始了。

Update

更新

Though with the help of serialization, they became able to send data using signals instead of actual spaceship, they realized that sending large set of data was still a challenge. Serialization make the process cheaper and faster but it was still slow. Hence the different scientists came up with different ideas to reduce the data size. Some scientists suggested to compress the data and some suggested to use different mechanism to represent it so it can be deserialized back. Some of the ideas are XML, JSON, msgpack, ????? (Nimn)

尽管在序列化的帮助下,他们能够使用信号而不是实际的飞船发送数据,但他们意识到发送大量数据仍然是一个挑战。序列化使该过程更便宜、更快,但仍然很慢。因此,不同的科学家想出了不同的想法来减少数据大小。一些科学家建议对数据进行压缩,一些科学家建议使用不同的机制来表示它,以便将其反序列化。一些想法是XMLJSONmsgpack????? (尼姆)

回答by Gagandeep Singh

And you can also implement object cloning using serialization

并且您还可以使用序列化来实现对象克隆

回答by user095736

Serialization generally referred as conversion of Object in to series of bits. it's an essential one in java since java mainly meant for web-based app's i mean to make the data to be available across the network

序列化通常称为将 Object 转换为一系列位。它是 Java 中必不可少的一个,因为 Java 主要用于基于 Web 的应用程序,我的意思是使数据在网络上可用

回答by Deplover

public class Serializer {

    public static void write(Object o, File f) throws IOException {
        f.delete();
        f.createNewFile();
        FileOutputStream fileOut = new FileOutputStream(f);
        ObjectOutputStream out = new ObjectOutputStream(fileOut);
        out.writeObject(o);
        out.close();
        fileOut.close();
    }

    public static Object read(File f) throws Exception{
        FileInputStream fileIn = new FileInputStream(f);
        ObjectInputStream in = new ObjectInputStream(fileIn);
        Object e = in.readObject();
        in.close();
        fileIn.close();
        return e;
    }

    public static byte[] toBytes(Object o) {
        byte[] bytes = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutput out = null;
        try {
            out = new ObjectOutputStream(bos);
            out.writeObject(o);
            out.flush();
            bytes = bos.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bos.close();
            } catch (IOException ex) {
                // ignore close exception
            }
        }

        return bytes;
    }

    public static Object fromBytes(byte[] bytes) {
        Object o = null;
        ByteArrayInputStream bis = new ByteArrayInputStream(bytes);
        ObjectInput in = null;
        try {
            in = new ObjectInputStream(bis);
            o = in.readObject();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                // ignore close exception
            }
        }

        return o;
    }
}

回答by Java By Kiran

Serialization is needed when there is a problem in sending data from one class to another. Where the other class is on a different location or Hard Disk. i.e. in Distributed Systems

当将数据从一个类发送到另一个类时出现问题时需要序列化。另一个类在不同的位置或硬盘上。即在分布式系统中

The reverse operation of serialisation is called deserialization

序列化的逆向操作称为反序列化

The String Class and all wrapper classes implement serializable interface by default

String 类和所有包装类默认实现可序列化接口

Serializable interface is also marker interface which provides the capability of Serialization to your class. So, we should implement a serializable interface if we want to send the state of an object over the network

Serializable 接口也是标记接口,它为您的类提供序列化功能。所以,如果我们想通过网络发送对象的状态,我们应该实现一个可序列化的接口