2019独角兽企业重金招聘Python工程师标准>>>
1.Java对象序列化是将 对象的实例域数据( 包括private私有域) 进行持久化存储。而并非是将整个对象所属的类信息进行存储。
2.我们都知道凡要序列化的类都必须实现Serializable接口。包括Externalizable接口
3.包含了不可序列化的对象域的对象也是不能序列化的。
实现Externalizable接口的类完全由自身来控制序列化的行为,而仅实现Serializable接口的类可以采用默认的序列化方式
对象序列化包括如下步骤:
1) 创建一个对象输出流,它可以包装一个其他类型的目标输出流,如文件输出流;
2) 通过对象输出流的writeObject()方法写对象。
对象反序列化的步骤如下:
1) 创建一个对象输入流,它可以包装一个其他类型的源输入流,如文件输入流;
2) 通过对象输入流的readObject()方法读取对象。
相比Serializable接口,Externalizable接口更加能够控制序列化过程中的细节。
而本人实际测试中,Externalizable接口进行序列化,会比Serializable接口,速度要快20%-40%
写一个Externalize序列化的Example:
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectOutput;
public class Customer implements Externalizable {
private String name;
private int age;
public Customer(){
//必须创建一个无参的构造函数,因为Externalizable在创建对象的时候,会调用构造函数。
//否则会报错java.io.InvalidClassException no valid constructor
}
public Customer(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "name=" + name + ", age=" + age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return this.name;
}
public int getAge() {
return this.age;
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
String name = in.readUTF();
int age = in.readInt();
this.setName(name);
this.setAge(age);
}
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeUTF(this.name);
out.writeInt(this.age);
}
}
调用端测试:
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;
public class ObjectSerializeTest {
public void saveCustomer() throws FileNotFoundException,
IOException {
File file = new File("D:/objectFile.obj");
if(file.exists())
file.delete();
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(
"D:/objectFile.obj"));
// 序列化对象
Customer2 c = new Customer2("阿蜜果", 24);
out.writeObject(c);
out.close();
}
public Customer2 getCustomer() throws FileNotFoundException, IOException,
ClassNotFoundException {
// 反序列化对象
ObjectInputStream in = new ObjectInputStream(new FileInputStream(
"D:/objectFile.obj"));
Customer2 customer = (Customer2) in.readObject();
in.close();
return customer;
}
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
int counter = 10000;
ObjectSerializeTest test = new ObjectSerializeTest();
test.saveCustomer();
long startTime=System.currentTimeMillis(); //获取开始时间
for(int i=0;i<counter;i++)
test.getCustomer();
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(endTime-startTime)+"ms");
}
}
refer to:http://hxraid.iteye.com/blog/461935