Static member problems in serialization and deserialization in Java __java

Source: Internet
Author: User
Tags object serialization serialization
static member problems in serialization and deserialization in Java
About the title of the content is the interview written in the more common questions, you follow my blog to learn the next process.
Serialization and deserialization in Java are primarily used to:
(1) Write the object or exception to the file, transfer the information through the file, and (2) transmit the object or the exception through the network.
So why do you need serialization and deserialization? In short, serialization and deserialization are unnecessary if you are using the same JVM to operate in the same environment as the same machine, and it is necessary to transfer data. For example, your data is written to the file to be used by other people's computer programs, or the data on your computer needs to be transmitted through the network to other people's programs to use, such as Server client model is an application, this time, we think, everyone's computer configuration may be different, the operating environment may also be different, The byte sequence may also be different, in short, many places can not be consistent, so for the sake of unification, we transmit data or file-saved data need to be serialized and coded, and so on, equivalent to the interaction between the two sides have a public standard, according to this standard to do, regardless of their environment is different, Each can translate the correct data that they can understand according to the standard.
In Java, there are APIs dedicated to this type of operation, which can be used directly by the developer, and the serialization and deserialization of objects may be read and written using the object's input and output stream by implementing the Serializable interface, followed by a complete example.
Package test2;

Import java.io.Serializable;

public class DataObject implements Serializable {
	
	/**
	 * Serialized UID number */
	private static final long Serialversionuid = -3737338076212523007l;
	
	public static int i =  0;
	Private String Word = "";
	
	public static void SetI (int i) {
		dataobject.i = i;
	}
	
	public void Setword (String word) {
		This.word = Word;
	}
	
	public static int Geti () {return
		i;
	}
	Public String Getword () {return
		word;
	}

	@Override public
	String toString () {return
		"word =" + Word + "," + "i =" + i;
	}

}

The above program defines the class DataObject to be serialized and deserialized, and this class implements the Serializable interface, which has several points to note:
(1) class has a static member variable I, this variable can be serialized. Wait and see through the test program; (2) The ToString method is overridden in the class to print the results.
Let's take a look at a beta version of the object that tests the serialization and deserialization of the class, which in advance indicates that this version is problematic.
Package test2;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;

Import Java.io.ObjectOutputStream; /** * Description: Serialization and reverse sequence of test objects/public class Testobjserializeanddeserialize {public static void main (string[) a
        
        RGS) throws Exception {//Serialization DataObject object Serialize ();
        
        DataObject object = Deserialize () for reverse sequence DataObject objects; Static members belong to the class level, so it can't be serialized, serialization is just serializing the object,//the inability to serialize here means that the serialization information does not contain the static member field, and the following/I output is 2 because the test is in the same machine (and the same one Process), because this JVM//has already loaded I in, I get the loaded I, if it is uploaded to another machine or turn off the program and write a program to read DataObject.txt, because the other machine or the new process is reloaded I, so I information
    Is the initial information, that is, 0 System.out.println (object); /** * Methodname:serializeperson * Description: Serializing the Person object * @author * @throws FILENOTF
   Oundexception * @throws IOException * * private static void Serialize () throws FileNotFoundException, IOException {DataObject object = new DataObject
    	();
    	Object.setword ("123");
    	
        Object.seti (2); Creates the ObjectOutputStream object output stream, which uses the file descriptor object and the file output stream object ObjectOutputStream oo = new ObjectOutputStream (New FILEOUTPUTST
        
        Ream (New File ("DataObject.txt"));
        
        The DataObject object is stored in the DataObject.txt file to complete the serialization operation of the DataObject object Oo.writeobject (object); System.out.println ("Person object serialization succeeded.")
        
        ");
        Finally, you must remember to close the object descriptor ...
    Oo.close ();  /** * Methodname:deserializeperson * Description: Reverse sequence DataObject Object * @author * @return * @throws Exception * @throws ioexception/private static DataObject deserialize () throws Exception, Ioexce ption {///Create ObjectInputStream object input stream with file descriptor object and file input Stream object ObjectInputStream ois = new Objectinputstrea M (New FileInputStream (new File)("DataObject.txt"));
        Reads the DataObject object from the DataObject.txt file, completes the deserialization operation of the DataObject object DataObject object = (DataObject) ois.readobject (); System.out.println ("The person object deserialized successfully.")
        
        ");
        Finally, you must remember to close the object descriptor ...
        
        Ois.close ();
    return object; }

}

The above procedure can be run directly. Note that there are two methods serialize () and deserialize (), respectively, to achieve serialization and deserialization functions, which mainly used the object input and output stream and file input and output stream, you can see the comments in the program to understand. In the serialized method, the object's member variable word is set to "123". I was set to "2", notice that I is a static variable here, so the usual serialization and deserialization understanding is nothing more than a positive process and an inverse process, after the final deserialization, Output objects in Word and I, we generally feel that should still be "123" and "2", then the results of the above program is indeed:
Word = "123", I = 2
This will make people think that this is the case, in fact, this is wrong. Keep in mind that static members are class-level, so they cannot be serialized, serialization is just a serialization of objects, where "not serializable" means that the serialization information does not contain this static member domain, and the reason I output is 2, because the tests are on the same machine (and the same process) because the JV M has loaded me in, so get the loaded I, if it's uploaded to another machine or turn off the program and read into DataObject.txt, because the other machine or the new process is reloading I, so I information is the initial information, that is, 0. So, to sum it up, static members cannot be serialized, and the default initial value of a static member is 0, so the correct run result should be:
Word = "123", I = 0

So how can we test the right results? It is noted that the above program is directly in a JVM in the process of serialization and deserialization of all processes, so the JVM has been saved i = 2, so the value of I did not change, so read it again is definitely 2. If you want to get the right results, you have to test in two JVMs, but it's hard for everyone's computer to do this test environment, so you can test it in the following ways.
Package test2;
Import Java.io.File;
Import java.io.FileNotFoundException;
Import Java.io.FileOutputStream;
Import java.io.IOException;

Import Java.io.ObjectOutputStream; /** * Description: Serialization of Test objects/public class Serializedataobject {public static void main (string[] args) throws exc
        
    Eption {//Serialization of DataObject Objects Serialize (); /** * Methodname:serializeperson * Description: Serializing the Person object * @author * @throws FILENOTF Oundexception * @throws IOException * * private static void Serialize () throws FileNotFoundException, Ioexcep
    	tion {DataObject object = new DataObject ();
    	Object.setword ("123");
    	
        Object.seti (2); Creates the ObjectOutputStream object output stream, which uses the file descriptor object and the file output stream object ObjectOutputStream oo = new ObjectOutputStream (New FILEOUTPUTST
        
        Ream (New File ("DataObject.txt")); The DataObject object is stored in the DataObject.txt file to complete the serialization of the DataObject object Oo.writeobjeCT (object); System.out.println ("Person object serialization succeeded.")
        
        ");
        Finally, you must remember to close the object descriptor ...
    Oo.close (); }
}

The above class is used only for serialization, the object is serialized and saved in the file "DataObject.txt", and then the program runs and the JVM exits. Next, look at another procedure.
Package test2;
Import Java.io.File;
Import Java.io.FileInputStream;
Import java.io.IOException;

Import Java.io.ObjectInputStream; /** * Description: The reverse sequence of the test object/public class Deserializedataobject {public static void main (string[] args) throws E
        
        xception {//Inverse sequence DataObject objects DataObject object = Deserialize (); Static members belong to the class level, so it can't be serialized, serialization is just serializing the object,//the inability to serialize here means that the serialization information does not contain the static member field, and the following/I output is 2 because the test is in the same machine (and the same one Process), because this JVM//has already loaded I in, I get the loaded I, if it is uploaded to another machine or turn off the program and write a program to read DataObject.txt, because the other machine or the new process is reloaded I, so I information
    Is the initial information, that is, 0 System.out.println (object);  /** * Methodname:deserializeperson * Description: Reverse sequence DataObject Object * @author * @return * @throws Exception * @throws ioexception/private static DataObject deserialize () throws Exception, Ioexce ption {///Create ObjectInputStream object input stream with file descriptor object and file input stream object ObjectInputStream ois= new ObjectInputStream (New FileInputStream ("DataObject.txt"));
        Reads the DataObject object from the DataObject.txt file, completes the deserialization operation of the DataObject object DataObject object = (DataObject) ois.readobject (); System.out.println ("The person object deserialized successfully.")
        
        ");
        Finally, you must remember to close the object descriptor ...
        
        Ois.close ();
    return object; }

}

The above program is used to deserialize objects, it reads the information about the object from the file "DataObject.txt" and then deserializes it, and the final output is the value of Word and I, the result of which is Word = "123", I = 0 This is the correct result, This is because both serialization and deserialization have their own main method, serialized first, then the JVM exits, runs deserialization again, the JVM reloads the DataObject class, when i = 0, the "DataObject.txt" file actually has no I information, only word information. This allows the JVM to get an opportunity to reload the class, simulating the results of running under two JVMs, by sequentially executing serialization and deserialization.
In conclusion, we should keep the following points in mind:
(1) The implementation method and application of serialization and deserialization; (2) Static members cannot be serialized, because static members are loaded with the class, the class survives, and the default initial value of the static member is 0; (3) to understand the cause of the wrong test program, understand some of the basic mechanisms of the JVM (4) To override the ToString method if you want to output some of the object's property information directly by printing the object.
Above is just some of my personal summary, welcome to correct and Add.
Related Article

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.