对象序列化是把一个对象转变为二进制数据流 的一种方法,而一个对象想要被序列化就需要实现Serializable接口。
查看Serializable接口的源码可以看到,并没有定义任何的方法,这是一个标识的接口:
public interface Serializable {
}
下面我们定义一个类
public class Person implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1073458546087797538L;
private String name;
private int age;
public Person(String name,int age){
this.name=name;
this.age=age;
}
public String toString(){
return "姓名:"+this.name+":年龄"+this.age;
}
}
这个类就实现了序列化的接口,可以看到在这个类里面我们定义了一个
serialVersionUID = 1073458546087797538L
一般来说,因为使用者jdk的不同,序列化和反序列化的版本不一致时就会出现异常,因此就加了这么一个常量来对版本一致性进行验证。如果在没有定义serialVersionUID时,java的序列化机制会默认的定义一个serialVersionUID值,下面是在serialVersion类中对serialVersionUID的详细介绍:
* This readResolve method follows the same invocation rules and
* accessibility rules as writeReplace.<p>
*
* The serialization runtime associates with each serializable class a version
* number, called a serialVersionUID, which is used during deserialization to
* verify that the sender and receiver of a serialized object have loaded
* classes for that object that are compatible with respect to serialization.
* If the receiver has loaded a class for the object that has a different
* serialVersionUID than that of the corresponding sender's class, then
* deserialization will result in an {@link InvalidClassException}. A
* serializable class can declare its own serialVersionUID explicitly by
* declaring a field named <code>"serialVersionUID"</code> that must be static,
* final, and of type <code>long</code>:
*
* <PRE>
* ANY-ACCESS-MODIFIER static final long serialVersionUID = 42L;
* </PRE>
*
* If a serializable class does not explicitly declare a serialVersionUID, then
* the serialization runtime will calculate a default serialVersionUID value
* for that class based on various aspects of the class, as described in the
* Java(TM) Object Serialization Specification. However, it is <em>strongly
* recommended</em> that all serializable classes explicitly declare
* serialVersionUID values, since the default serialVersionUID computation is
* highly sensitive to class details that may vary depending on compiler
* implementations, and can thus result in unexpected
* <code>InvalidClassException</code>s during deserialization. Therefore, to
* guarantee a consistent serialVersionUID value across different java compiler
* implementations, a serializable class must declare an explicit
* serialVersionUID value. It is also strongly advised that explicit
* serialVersionUID declarations use the <code>private</code> modifier where
* possible, since such declarations apply only to the immediately declaring
* class--serialVersionUID fields are not useful as inherited members. Array
* classes cannot declare an explicit serialVersionUID, so they always have
* the default computed value, but the requirement for matching
* serialVersionUID values is waived for array classes.
*
大致上就是介绍需要一致,不一致会出现异常,而且必须是static,final,long。而这个值一致与否会对下面造成什么影响在下面我们继续写
而要完成对象的输入和输出,还需要使用对象输出流ObjectOutputStream和对象输入流ObjectInputStream,demo1进行输入
public class Demo1 {
/**
* @param args
*/
public static void main(String[] args) throws IOException{
// TODO 自动生成的方法存根
File file=new File("d:"+File.separator+"test.txt");
ObjectOutputStream oos=null;
OutputStream out=new FileOutputStream(file);
oos=new ObjectOutputStream(out);
oos.writeObject(new Person("张三", 30));
oos.close();
}
}
输入数据以后,打开文件可以看到,记录的是一串二进制的乱码
demo2输出
public class Demo2 {
/**
* @param args
*/
public static void main(String[] args) throws Exception{
// TODO 自动生成的方法存根
File file=new File("d:"+File.separator+"test.txt");
InputStream input=new FileInputStream(file);
ObjectInputStream objectInputStream=new ObjectInputStream(input);
Object object=objectInputStream.readObject();
objectInputStream.close();
System.out.println(object);//姓名:张三:年龄30
}
}
在两边的码一致的情况下,不会出现任何问题。我们把上面的uid最后一位去掉,运行程序就会出现下面的异常:
Exception in thread "main" java.io.InvalidClassException: test.Person; local class incompatible: stream classdesc serialVersionUID = 1073458546087797538, local class serialVersionUID = 107345854608779753
Serializable中所有的对象都必须被序列化,如果想进行部分序列化的话该怎么办?Externalizable接口是可以实现部分对象的序列化,这个接口定义了两个方法,writeExternal(ObjectOutput out)用来保存信息,readExternal(ObjectInput in)用来读取,反序列化对象。
public interface Externalizable extends java.io.Serializable {
void writeExternal(ObjectOutput out) throws IOException;
void readExternal(ObjectInput in) throws IOException, ClassNotFoundException;
}
在Externalizable接口接口中是必须要定义无参构造的,在其进行反序列化的时候会调用,否则就会出现异常。
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class Person implements Externalizable {
private static final long serialVersionUID = -842029427676826563L;
public static String name;
private int age;
private transient int workDay = 5;
private String fClub;
public Person() {
System.out.println("无参构造");
}
public Person(int age, String fClub) {
this.age = age;
this.fClub = fClub;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWorkDay() {
return workDay;
}
public void setWorkDay(int workDay) {
this.workDay = workDay;
}
public String getfClub() {
return fClub;
}
public void setfClub(String fClub) {
this.fClub = fClub;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();//执行默认的序列化机制
out.writeInt(workDay);
System.out.println("正在进行序列持久化");
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
workDay = in.readInt();
System.out.println("读取持久化对象");
}
@Override
public void readExternal(ObjectInput arg0) throws IOException,
ClassNotFoundException {
// TODO Auto-generated method stub
}
@Override
public void writeExternal(ObjectOutput arg0) throws IOException {
// TODO Auto-generated method stub
}
}
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Hello {
public static void main(String[] args) {
Person person = new Person(26, "Juventus");
person.setWorkDay(7);
try {
FileOutputStream fs = new FileOutputStream("foo.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(person);
os.close();
Person.name = "Alex";
FileInputStream in = new FileInputStream("foo.ser");
ObjectInputStream s = new ObjectInputStream(in);
Person p = (Person) s.readObject();
System.out.println("name==" + Person.name + " age==" + p.getAge()
+ " workDay==" + p.getWorkDay() + " fClub==" + p.getfClub());
} catch (Exception e) {
e.printStackTrace();
}
}
}
输出结果
无参构造
name==Alex age==0 workDay==5 fClub==null
可以看到,在Person p = (Person) s.readObject();这一步调用了无参构造person方法。而因为在foo.ser文件中只有类的类型声明,没有任何实例变量,所以Person对象中任何一个字段都没有被序列化,所以打印结果里面,age为0,fClub为null,而workDay为初始值5。writeExternal()与readExternal()方法未作任何处理,那么该序列化行为将不会保存/读取任何一个字段。
修改person类
package test;
import java.io.Externalizable;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
public class Person implements Externalizable {
private static final long serialVersionUID = -842029427676826563L;
public static String name;
private int age;
private transient int workDay = 5;
private String fClub;
public Person() {
System.out.println("无参构造");
}
public Person(int age, String fClub) {
this.age = age;
this.fClub = fClub;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public int getWorkDay() {
return workDay;
}
public void setWorkDay(int workDay) {
this.workDay = workDay;
}
public String getfClub() {
return fClub;
}
public void setfClub(String fClub) {
this.fClub = fClub;
}
/*private void writeObject(ObjectOutputStream out) throws IOException {
out.defaultWriteObject();//执行默认的序列化机制
out.writeInt(workDay);
System.out.println("正在进行序列持久化");
}
private void readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
in.defaultReadObject();
workDay = in.readInt();
System.out.println("读取持久化对象");
}*/
@Override
public void writeExternal(ObjectOutput out) throws IOException {
out.writeObject(fClub);
out.writeInt(age);
System.out.println("自定义序列化过程");
}
@Override
public void readExternal(ObjectInput in) throws IOException,
ClassNotFoundException {
fClub = (String) in.readObject();
age = in.readInt();
System.out.println("自定义反序列化");
}
}
结果:
自定义序列化过程
无参构造
自定义反序列化
name==Alex age==26 workDay==5 fClub==Juventus
当读取对象时,会调用被序列化类的无参构造器去创建一个新的对象,然后再将被保存对象的字段的值分别填充到新对象中。这就是为什么输出结果中会显示调动了无参构造器。由于这个原因,实现Externalizable接口的类必须要提供一个无参的构造器,且它的访问权限为public。
实现Externalizable接口是可以进行对象的部分序列化,但是其操作起来比serializable复杂麻烦,而使用serializable又会遇到例如在某些情况下我们会遇到密码等我们不希望被序列化的对象,这些信息对应的变量就可以加上transient关键字。换句话说,这个字段的生命周期仅存于调用者的内存中而不会写到磁盘里持久化。
觉得不错是可以点个赞。