PackageCom.phone.shuyinghengxie;Importjava.io.Serializable;/*for a class object to be serialized successfully, two conditions must be met: the class must implement a Java.io.Serializable object. All properties of the class must be serializable. If there is a property that is not serializable, the attribute must be noted to be short-lived. If you want to know if a Java standard class is serializable, see the documentation for that class. It is very simple to verify that an instance of a class can be serialized, just to see if the class implements the Java.io.Serializable interface. */ Public classEmployeeImplementsjava.io.serializable{ PublicString name; PublicString address; Public transient intSSN; Public intNumber ; Public voidMailCheck () {System.out.println ("Mailing a check to" +name+ " " +address); }}
/*The serialized object ObjectOutputStream class is used to serialize an object, as the following Serializedemo example instantiates an employee object and serializes the object into a file. After the program executes, a file named Employee.ser is created. The program does not have any output, but you can read through the code to understand the role of the program. Note: When serializing an object to a file, the standard convention in Java is to give the file a. ser extension. */ Public classserializedemo{ Public Static voidmain (String [] args) {Employee e=NewEmployee (); E.name= "Reyan Ali"; E.address= "Phokka Kuan, Ambehta Peer"; E.SSN= 11122333; E.number= 101; Try{FileOutputStream fileout=NewFileOutputStream ("/tmp/employee.ser"); ObjectOutputStream out=NewObjectOutputStream (fileout); Out.writeobject (e); Out.close (); Fileout.close (); System.out.printf ("Serialized data is saved In/tmp/employee.ser"); }Catch(IOException i) {i.printstacktrace (); } }}
/*The Deserializedemo program instance below the deserialization object is deserialized, and/tmp/employee.ser stores the employee object. */ Public classdeserializedemo{ Public Static voidmain (String [] args) {Employee e=NULL; Try{FileInputStream Filein=NewFileInputStream ("/tmp/employee.ser"); ObjectInputStream in=NewObjectInputStream (Filein); E=(Employee) in.readobject (); In.close (); Filein.close (); }Catch(IOException i) {i.printstacktrace (); return; }Catch(classnotfoundexception c) {System.out.println ("Employee Class not Found"); C.printstacktrace (); return; } System.out.println ("Deserialized Employee ..."); System.out.println ("Name:" +e.name); System.out.println ("Address:" +e.address); System.out.println ("SSN:" +e.ssn); System.out.println ("Number:" +e.number); }}
serialization, deserialization (an entity class or an object class to be serialized must implement the Serializable interface)