Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
This post was edited and submitted for review 2 days ago.
Improve this questionCan anyone tell me what is the need of Serialization of objects in Java and give me an example sc开发者_C百科enario to explain the need? (I already understand what serialization is, I just want to understand when you'd use it and how'd use it?).
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.
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 serialized the data of each robot and sent it to earth. Earth's scientists deserialized the 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 transient before 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.
One more point noticed by Earth's scientists is that Mars' scientists asked them to create some static variables to 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.
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)
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.
Serialization is the translation of your Java object's values/states to bytes to send it over network or save it.
This is analogous to how your voice is transmitted over PSTN telephone lines.
Java serialization (and, specifically, the Serializable and Exernalizable interfaces) 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)
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).
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.
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 buffers and MessagePack are 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.
Usage
Since you asked for the need, not merely the definition, there are a number of use cases:
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).
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.
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.
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.
Examples when you need this: Caching objects, making remote method calls, saving an object graph to disk.
- 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.
And you can also implement object cloning using serialization
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
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;
}
}
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
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
精彩评论