package cm;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Date;;
public class test20180425Externalizable {
//当调用Objectoutputstream的writeObject()方法的时候,会默认调用缺省的writeObject()方法。如果你要序列化的对象添加了一个writeobject()方法。则会调用你添加的
//writeobject()方法。//这里使用添加的writeobject方法使得transient修饰的对象能序列。因为缺省的writeobject方法不序列化transient字段。
//class类对象默认继承serializable接口的。缺省序列化方法不能序列化static字段。
public static void main(String[] args) {
Date date=new Date();
System.out.println(date);
try {
ObjectOutputStream out=new ObjectOutputStream(new FileOutputStream("D:\\ser.out"));
serializabletest sr=new serializabletest("bigseacoming","123");
out.writeObject(sr);
//输出序列化对象。
ObjectInputStream in=new ObjectInputStream(new FileInputStream("D:\\ser.out"));
serializabletest srin=(serializabletest) in.readObject();
System.out.println(srin.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
class serializabletest implements Serializable{
private String name;
private transient String password;
public serializabletest(String name,String password) {
this.name=name;
this.password=password;
}
private void writeObject(ObjectOutputStream out) {
try {
out.defaultWriteObject();
out.writeObject(password);
} catch (IOException e) {
e.printStackTrace();
}
}
private void readObject(ObjectInputStream in) throws IOException {
try {
in.defaultReadObject();
password=(String) in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public String toString() {
return "name:"+name+"\npassword:"+password;
}
}
缺省序列化
最新推荐文章于 2023-03-20 21:53:31 发布