深入剖析Java编程中的序列化
java提供一种机制叫做序列化,通过有序的格式或者字节序列持久化java对象,其中包含对象的数据,还有对象的类型,和保存在对象中的数据类型。
所以,如果我们已经序列化了一个对象,那么它可以被读取并通过对象的类型和其他信息进行反序列化,并最终获取对象的原型。
objectinputstream 和 objectoutputstream对象是高级别的流对象,包含序列化和反序列化的方法。
objectoutputstream 拥有很多序列化对象的方法,最常用的是:
private void writeobject(objectoutputstream os) throws ioexception { }
类似的 objectinputstream 提供如下方法:
private void readobject(objectinputstream is) throws ioexception, classnotfoundexception { }
那么哪里会需要序列化呢?序列化通常在需要通过网络传输数据,或者保存对象到文件的场合使用。这里说的数据是对象而不是文本。
现在的问题是,我们的网络架构和硬盘都只能识别二进制和字节,而不能识别java对象。
序列化就是把java对象中的value/states翻译为字节,以便通过网络传输或者保存。另外,反序列化就是通过读取字节码,并把它翻译回java对象。
serialversionuid概念
serialversionuid 是用于保证同一个对象(在序列化中会被用到)可以在deserialization过程中被载入。serialversionuid 是用于对象的版本控制。你可以参考serialversionuid in java serialization获取更多信息。
对于序列化:
步骤如下:
让我们看一个列子:
在 src->org.arpit.javapostsforlearning 创建employee.java
1.employee.java
package org.arpit.javapostsforlearning; import java.io.serializable; public class employee implements serializable{ int employeeid; string employeename; string department; public int getemployeeid() { return employeeid; } public void setemployeeid(int employeeid) { this.employeeid = employeeid; } public string getemployeename() { return employeename; } public void setemployeename(string employeename) { this.employeename = employeename; } public string getdepartment() { return department; } public void setdepartment(string department) { this.department = department; } }
就如你所见的,如果你需要序列化任何类,那么你 必须实现 serializable 接口 ,这个接口是标记接口(marker interface)。
java中的标记接口(marker interface)就是一个没有任何字段或者方法的接口,简单的来说,java中把空接口叫做标记接口(marker interface)
2.serializemain.java
package org.arpit.javapostsforlearning; import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectoutputstream; public class serializemain { /** * @author arpit mandliya */ public static void main(string[] args) { employee emp = new employee(); emp.setemployeeid(101); emp.setemployeename("arpit"); emp.setdepartment("cs"); try { fileoutputstream fileout = new fileoutputstream("employee.ser"); objectoutputstream outstream = new objectoutputstream(fileout); outstream.writeobject(emp); outstream.close(); fileout.close(); }catch(ioexception i) { i.printstacktrace(); } } }
对于反序列化:
步骤是
在包src->org.arpit.javapostsforlearning中,创建 deserializemain.java
3.deserializemain.java
package org.arpit.javapostsforlearning; import java.io.ioexception; import java.io.objectinputstream; public class deserializemain { /** * @author arpit mandliya */ public static void main(string[] args) { employee emp = null; try { fileinputstream filein =new fileinputstream("employee.ser"); objectinputstream in = new objectinputstream(filein); emp = (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("emp id: " + emp.getemployeeid()); system.out.println("name: " + emp.getemployeename()); system.out.println("department: " + emp.getdepartment()); } }
4.运行:
首先运行serializemain.java,然后运行 deserializemain.java,你会得到如下的结果:
deserialized employee... emp id: 101 name: arpit department: cs
就这样,我们序列化了一个employee对象,并对它进行反序列化。这看起来和简单,但是如果其中包含对象引用,继承,那么情况就会变得复杂。接下来让我们一个接一个的看一下例子,看看如何在各种场合中实现序列化。
案例1 - 如果对象引用了其他对象,那该如何
我们已经看过最简单的序列化例子,现在看看,如何处理对象中引用了其他对象的场合。我们该如何序列化?引用对象也会被序列化吗?对的,你不需要显式的序列化引用对象。当你序列化任何对象,如果它包含引用对象,那么java序列化会自动序列化该对象的整个对象图。例如,employee现在引用了一个address对象,并且address也引用了其他对象(例如,home),那么当你序列化employee对象的时候,所有其他引用对象,例如address和home将会被自动地被序列化。让我们来创建address类,并它address的对象作为引用,添加到employee类中。
employee.java:
package org.arpit.javapostsforlearning; import java.io.serializable; public class employee implements serializable{ int employeeid; string employeename; string department; address address; public int getemployeeid() { return employeeid; } public void setemployeeid(int employeeid) { this.employeeid = employeeid; } public string getemployeename() { return employeename; } public void setemployeename(string employeename) { this.employeename = employeename; } public string getdepartment() { return department; } public void setdepartment(string department) { this.department = department; } public address getaddress() { return address; } public void setaddress(address address) { this.address = address; } }
在 org.arpit.javapostsforlearning 包中,创建address.java
address.java:
package org.arpit.javapostsforlearning; public class address { int homeno; string street; string city; public address(int homeno, string street, string city) { super(); this.homeno = homeno; this.street = street; this.city = city; } public int gethomeno() { return homeno; } public void sethomeno(int homeno) { this.homeno = homeno; } public string getstreet() { return street; } public void setstreet(string street) { this.street = street; } public string getcity() { return city; } public void setcity(string city) { this.city = city; } }
在包 org.arpit.javapostsforlearning中,创建serializedeserializemain.java
serializedeserializemain.java:
package org.arpit.javapostsforlearning; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectinputstream; import java.io.objectoutputstream; public class serializedeserializemain { /** * @author arpit mandliya */ public static void main(string[] args) { employee emp = new employee(); emp.setemployeeid(101); emp.setemployeename("arpit"); emp.setdepartment("cs"); address address=new address(88,"mg road","pune"); emp.setaddress(address); //serialize try { fileoutputstream fileout = new fileoutputstream("employee.ser"); objectoutputstream outstream = new objectoutputstream(fileout); outstream.writeobject(emp); outstream.close(); fileout.close(); }catch(ioexception i) { i.printstacktrace(); } //deserialize emp = null; try { fileinputstream filein =new fileinputstream("employee.ser"); objectinputstream in = new objectinputstream(filein); emp = (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("emp id: " + emp.getemployeeid()); system.out.println("name: " + emp.getemployeename()); system.out.println("department: " + emp.getdepartment()); address=emp.getaddress(); system.out.println("city :"+address.getcity()); } }
运行它:
当你运行serializedeserializemain.java。你会得到这样的结果:
java.io.notserializableexception: org.arpit.javapostsforlearning.address at java.io.objectoutputstream.writeobject0(unknown source) at java.io.objectoutputstream.defaultwritefields(unknown source) at java.io.objectoutputstream.writeserialdata(unknown source) at java.io.objectoutputstream.writeordinaryobject(unknown source) at java.io.objectoutputstream.writeobject0(unknown source) at java.io.objectoutputstream.writeobject(unknown source)
我们将解释哪里出错了。我忘记了说,address 类也必须是serializable。那么address类必须继承serialzable接口。
address.java:
import java.io.serializable; public class address implements serializable{ int homeno; string street; string city; public address(int homeno, string street, string city) { super(); this.homeno = homeno; this.street = street; this.city = city; } public int gethomeno() { return homeno; } public void sethomeno(int homeno) { this.homeno = homeno; } public string getstreet() { return street; } public void setstreet(string street) { this.street = street; } public string getcity() { return city; } public void setcity(string city) { this.city = city; } }
再次运行:
当你再次运行serializedeserializemain.java。你可以得到如下的结果
deserialized employee... emp id: 101 name: arpit department: cs city :pune
案例2:如果我们不能访问引用对象的源代码(例如,你不能访问上面的address类的源码)
如果我们不能访问到address类,那么我们该如何在address类中实现serializable 接口?是否有另外的途径来实现呢?对的,你可以创建另外一个类,并继承address,然后让它继承serializable 接口,但是对于下面的情况,这个方案会失败:
如果引用类被定义为final
如果引用类引用了另外一个非可序列化的对象
那么,我们该如何序列化employee对象?解决的办法是,标记transient。如果你不需要序列化任何字段,只需把它标记为transient。
transient address address
在employee类中,标记了address为transient之后,运行程序。你会得到nullpointerexception,因为在反序列化过程中,address引用将会是null。
案例3 - 如果我仍然需要保存引用对象的状态呢?(例如address对象)
如果你在反序列化过程中,标记了address为transient,它将会返回null结果。但是如果你仍然需要保存它的状态,你就需要序列化address对象。 java序列化提供一个机制,如果你有特定签名的private方法,那么它们就会在序列化和反序列化过程中被调用,所以我们将重写employee类的writeobject和readobject方法,然后它们就会在employee对象序列化/反序列化过程中被调用。
employee.java:
package org.arpit.javapostsforlearning; import java.io.ioexception; import java.io.objectinputstream; import java.io.objectoutputstream; import java.io.serializable; public class employee implements serializable{ int employeeid; string employeename; string department; transient address address; public int getemployeeid() { return employeeid; } public void setemployeeid(int employeeid) { this.employeeid = employeeid; } public string getemployeename() { return employeename; } public void setemployeename(string employeename) { this.employeename = employeename; } public string getdepartment() { return department; } public void setdepartment(string department) { this.department = department; } public address getaddress() { return address; } public void setaddress(address address) { this.address = address; } private void writeobject(objectoutputstream os) throws ioexception, classnotfoundexception { try { os.defaultwriteobject(); os.writeint(address.gethomeno()); os.writeobject(address.getstreet()); os.writeobject(address.getcity()); } catch (exception e) { e.printstacktrace(); } } private void readobject(objectinputstream is) throws ioexception, classnotfoundexception { try { is.defaultreadobject(); int homeno=is.readint(); string street=(string) is.readobject(); string city=(string) is.readobject(); address=new address(homeno,street,city); } catch (exception e) { e.printstacktrace(); } } }
另外有一点需要牢记的,objectinputstream读取数据的顺序和objectoutputstream写入数据的顺序是一致的.
在包org.arpit.javapostsforlearning 中创建address.java
address.java:
package org.arpit.javapostsforlearning; import java.io.serializable; public class address { int homeno; string street; string city; public address(int homeno, string street, string city) { super(); this.homeno = homeno; this.street = street; this.city = city; } public int gethomeno() { return homeno; } public void sethomeno(int homeno) { this.homeno = homeno; } public string getstreet() { return street; } public void setstreet(string street) { this.street = street; } public string getcity() { return city; } public void setcity(string city) { this.city = city; } }
在包org.arpit.javapostsforlearning中创建serializedeserializemain.java
serializedeserializemain.java:
package org.arpit.javapostsforlearning; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectinputstream; import java.io.objectoutputstream; public class serializedeserializemain { /** * @author arpit mandliya */ public static void main(string[] args) { employee emp = new employee(); emp.setemployeeid(101); emp.setemployeename("arpit"); emp.setdepartment("cs"); address address=new address(88,"mg road","pune"); emp.setaddress(address); //serialize try { fileoutputstream fileout = new fileoutputstream("employee.ser"); objectoutputstream outstream = new objectoutputstream(fileout); outstream.writeobject(emp); outstream.close(); fileout.close(); }catch(ioexception i) { i.printstacktrace(); } //deserialize emp = null; try { fileinputstream filein =new fileinputstream("employee.ser"); objectinputstream in = new objectinputstream(filein); emp = (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("emp id: " + emp.getemployeeid()); system.out.println("name: " + emp.getemployeename()); system.out.println("department: " + emp.getdepartment()); address=emp.getaddress(); system.out.println("city :"+address.getcity()); } }
运行 :
当你运行serializedeserializemain.java.你会得到如下的结果:
deserialized employee... emp id: 101 name: arpit department: cs city :pune
现在我们就得到了address对象的状态,就如它被序列化前的一样。
序列化中的继承:
现在我们看看继承是如何影响序列化的。不管父类是不是可序列化,这将引出很多个例子。如果父类是非可序列化的,我们将如何处理,并且它是如何工作的。让我们看看例子。
我们将创建一个person.java,作为 employee的父类。
案例4: 如果父类是可序列化的
如果父类可序列化,那么所有的继承类将是可序列化的。
案例5: 如果父类为非可序列化呢?
如果父类为非可序列化的 ,那么我们的处理办法会很不一样。
如果父类为非可序列化的,那么它必然不会有参数构造函数。
person.java
package org.arpit.javapostsforlearning; public class person { string name="default"; string nationality; public person() { system.out.println("person:constructor"); } public person(string name, string nationality) { super(); this.name = name; this.nationality = nationality; } public string getname() { return name; } public void setname(string name) { this.name = name; } public string getnationality() { return nationality; } public void setnationality(string nationality) { this.nationality = nationality; } }
在包org.arpit.javapostsforlearning 中创建employee.java
employee.java:
package org.arpit.javapostsforlearning; import java.io.serializable; public class employee extends person implements serializable{ int employeeid; string department; public employee(int employeeid,string name,string department,string nationality) { super(name,nationality); this.employeeid=employeeid; this.department=department; system.out.println("employee:constructor"); } public int getemployeeid() { return employeeid; } public void setemployeeid(int employeeid) { this.employeeid = employeeid; } public string getdepartment() { return department; } public void setdepartment(string department) { this.department = department; } }
在org.arpit.javapostsforlearning包中创建serializedeserializemain.java
serializedeserializemain.java:
package org.arpit.javapostsforlearning; import java.io.fileinputstream; import java.io.fileoutputstream; import java.io.ioexception; import java.io.objectinputstream; import java.io.objectoutputstream; public class serializedeserializemain { /** * @author arpit mandliya */ public static void main(string[] args) { //serialize employee emp = new employee(101,"arpit","cs","indian"); system.out.println("before serializing"); system.out.println("emp id: " + emp.getemployeeid()); system.out.println("name: " + emp.getname()); system.out.println("department: " + emp.getdepartment()); system.out.println("nationality: " + emp.getnationality()); system.out.println("************"); system.out.println("serializing"); try { fileoutputstream fileout = new fileoutputstream("employee.ser"); objectoutputstream outstream = new objectoutputstream(fileout); outstream.writeobject(emp); outstream.close(); fileout.close(); }catch(ioexception i) { i.printstacktrace(); } //deserialize system.out.println("************"); system.out.println("deserializing"); emp = null; try { fileinputstream filein =new fileinputstream("employee.ser"); objectinputstream in = new objectinputstream(filein); emp = (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("after serializing"); system.out.println("emp id: " + emp.getemployeeid()); system.out.println("name: " + emp.getname()); system.out.println("department: " + emp.getdepartment()); system.out.println("nationality: " + emp.getnationality()); } }
运行:
当你运行serializedeserializemain.java后,你会得到如下的输出,如果父类是非可序列化的,那么在反序列化过程中,所有继承于父类的实例变量值,将会通过调用非序列化构造函数来初始化。 这里 name继承于person,所以在反序列化过程中,name将会被初始化为默认值。
案例6 - 如果父类是可序列化,但你不需要继承类为可序列化
如果你不希望继承类为可序列化,那么你需要实现 writeobject() 和readobject() 方法,并且需要抛出notserializableexception 异常。
案例7 - 可否序列化静态变量?
不能。因为静态变量是类级别的,不是对象级别的,当你序列化一个对象的时候,是不能序列化静态变量。
总结:
- 序列化是java对象的values/states转化为字节并在网络中传输或者保存它的过程。另外反序列化是把字节码翻译为对应的对象的过程。
- 序列化的好处是,jvm的独立性,也就是说,一个对象可以在一个平台中被序列化,然后在另外一个不同的平台反序列化。
- 如果你需要序列化任何对象,你必须实现标记接口serializable。
- java中的标记接口(marker interface)就是没有字段或者方法的接口,或者更简单的说,空接口
- serialversionuid 是用于保证同一个对象(在序列化中会被用到)可以在deserialization过程中被载入。serialversionuid 是用于对象的版本控制。
- 当你需要序列化任何包含引用对象的对象,那么java会自动序列化该对象的整个对象图。
- 如果你不希望序列化某个字段,你可以标记它为trasient
- 如果父类为可序列化,那么它的继承类也将是可序列化的。
- 如果父类为非可序列化,那么在反序列化过程中,所有继承于父类的实例变量值将会通过调用非可序列化的构造器来初始化。
- 如果你需希望子类为可序列化的,那么你需要实现writeobject() 和 readobject() 方法,并在这两个方法中抛出notserializableexception异常
- 你不能序列化静态变量。
上一篇: 轻松实现Android语音识别功能