Java object concatenation

Source: Internet
Author: User

Java 1.1 Adds an interesting feature called Object Serialization (serialization). It targets objects that implement the serializable interface, converts them to a sequence of bytes, and returns to their original appearance completely later. This process can also be done through the network. This means that the serialization mechanism can automatically compensate for differences between operating systems. In other words, you can first create an object on a Windows machine, serialize it, and then send it over the network to a UNIX machine, where it is correctly reassembled. You don't have to worry about how data is represented on different machines, or about the order of bytes or any other detail.
In itself, the serialization of objects is interesting because it enables "finite persistence". Remember that "persistence" means that the "live time" of an object does not depend on whether the program is executing-it exists or "survives" between each invocation of the program. By serializing an object, writing it to disk, and then restoring that object again when the program is called again, you can achieve a "lasting" effect successfully. It is called "limited" because it is not possible to simply define an object with some kind of "persistent" (persistent) keyword, and to have the system automatically look after all other details (although it may become a reality in the future). Instead, you must explicitly serialize and assemble the object in your own program.
The concept of object serialization is added to the language to provide support for both of the main features. The "Remote Method call" (RMI) of Java 1.1 enables objects that would otherwise exist on other machines to behave as if they were on the local machine. When sending a message to a remote object, the parameters and return values are transmitted through object serialization. RMI will be specifically discussed in chapter 15th.
The serialization of objects is also required by Java beans, which is introduced by Java 1.1. When you use a bean, its state information is typically configured during design time. After the program is started, this state information must be saved so that the program can be restored after it is started, and the specific work is done by object serialization.
The serialization of an object is very simple, just the object implements the serializable interface (the interface is just a tag, no method). In Java 1.1, many of the standard library classes have changed so that they can be serialized-including all the wrappers for the base data type, all the collection classes, and many other things. Even class objects can be serialized (the 11th chapter describes the specific implementation process).
To serialize an object, you first create some OutputStream objects and then encapsulate them within the ObjectOutputStream object. At this point, you can simply call WriteObject () to complete the serialization of the object and send it to outputstream. The opposite process is to encapsulate a inputstream into ObjectInputStream, and then Invoke ReadObject (). As always, we end up with a handle that points back to the Shape object, so it has to be traced so that it can be set directly.
One place where object serialization is particularly "smart" is that it not only preserves the "panorama" of the object, but also tracks all the handles contained within the object and saves those objects, followed by tracking the handles contained within each object; We sometimes refer to this as the "Object Net", where a single object can be connected. It also contains an array of handle objects and member objects. If you have to manipulate a set of object serialization mechanisms on your own, it can be cumbersome to track all of these links in your code. On the other hand, because the serialization of Java objects seems to find no fault, so try not to do it yourself, so that it uses the optimized algorithm to automatically maintain the entire object network. The following example tests the serialization mechanism. It creates a "worm" of many linked objects, each linked to the next link in worm, and to an array of object handles belonging to different classes (Data):

: Worm.java//Demonstrates object serialization in Java 1.1 import java.io.*;
  Class Data implements Serializable {private int i;
  Data (int x) {i = x;}
  Public String toString () {return integer.tostring (i); } public class Worm implements Serializable {//Generate a random int value:private static int R () {return (
  int) (Math.random () * 10);
  Private data[] D = {new data (R)), new data (R ()), new data (R ())};
  Private Worm Next;
  private char C;
    Value of i = = number of segments worm (int i, char x) {System.out.println ("Worm constructor:" + i);
    c = x;
  if (i > 0) next = new Worm (i, (char) (x + 1));
  Worm () {System.out.println ("Default constructor");
    public string toString () {string s = ": + C +" (";
    for (int i = 0; i < d.length i++) s + = d[i].tostring ();
    s + = ")";
    if (next!= null) s + = next.tostring ();
  return s; public static void Main (string[] args) {WoRM w = new Worm (6, ' a ');
    System.out.println ("w =" + W);
      try {objectoutputstream out = new ObjectOutputStream (New FileOutputStream ("Worm.out"));
      Out.writeobject ("Worm storage");
      Out.writeobject (w); Out.close (); Also flushes output ObjectInputStream in = new ObjectInputStream (New FileInputStream ("Worm.out
      "));
      string s = (string) in.readobject ();
      Worm W2 = (worm) in.readobject ();
    SYSTEM.OUT.PRINTLN (S + ", W2 =" + W2);
    catch (Exception e) {e.printstacktrace ();
      try {bytearrayoutputstream bout = new Bytearrayoutputstream ();
      ObjectOutputStream out = new ObjectOutputStream (bout);
      Out.writeobject ("Worm storage");
      Out.writeobject (w);
      Out.flush (); ObjectInputStream in = new ObjectInputStream (New Bytearrayinputstream (Bout.tobytearray ()))
      ;
      string s = (string) in.readobject (); Worm W3 =(Worm) In.readobject ();
    SYSTEM.OUT.PRINTLN (S + ", W3 =" + W3);
    catch (Exception e) {e.printstacktrace (); }
  }
} ///:~

More interestingly, the data object array in worm is initialized with random numbers (so you don't have to suspect that the compiler retains some sort of raw information). Each worm segment is marked with a char. This char is generated automatically when a linked worm list is repeatedly generated. When you create a worm, tell the builder how long it is expected to be. To produce the next handle (next), it always calls the Worm builder with a length minus 1. The last next handle remains null (empty), indicating that the worm's tail has arrived.
All of the above actions are to deepen the complexity of the matter, increasing the difficulty of object serialization. However, the real serialization process is very simple. Once the Objectoutputstream,writeobject () is created from another stream, the object is serialized. Note You can also call WriteObject () for a string. You can also write all the basic data types (they have the same interface) using the same method as DataOutputStream.
There are two separate try blocks that look similar. The first reads and writes the file, while the other reads and writes a bytearray (byte array). You can use serialization of any datainputstream or dataoutputstream to read and write to a specific object, as in the chapter on networking, which even includes the network. The output after one cycle is as follows:

Worm constructor:6 worm
constructor:5 worm constructor:4 worm constructor:3 worm
constructor:2
Worm constructor:1
w =: A (262): B (M): C (396):d (): E (316): F (398)
Worm storage, W2 =: A (262): B (M): C (396):d ( ): E (316): F (398)
Worm storage, W3 =: A (262): B (M): C (396):d (i): E (316): F (398)

As you can see, the objects that are assembled back to the original do contain all the links contained in that object.
Note in the process of reassembling a serializable (serializable) object, no builders (or even default builders) are invoked. The entire object is recovered by obtaining data from the InputStream.
As one of the Java 1.1 features, we note that the serialization of objects is not part of the new reader and writer hierarchy, but rather the old-fashioned inputstream and outputstream structures. So in some special situations, you have to mix two types of hierarchies.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.