【java】对象序列化Serializable、transient

时间:2021-09-01 02:45:39
 package 对象序列化;

 import java.io.Serializable;

 @SuppressWarnings("serial")
class A implements Serializable{ }
public class TestSerializable {
public static void main(String[] args) { }
}

对象序列化:java.io.ObjectOutputStream

对象反序列化:java.io.ObjectInputStream

 package 对象序列化;

 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;
import java.io.Serializable; @SuppressWarnings("serial")
class A implements Serializable{
private String name;
private transient int age;//transient修饰的成员不能被序列化
public A(String name,int age){
this.name=name;
this.age=age;
}
@Override
public String toString() {
return "name="+name+",age="+age;
}
}
public class TestSerializable {
public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException {
ObjectOutputStream oos=new ObjectOutputStream(new FileOutputStream(new File("D:"+File.separator+"A.ser")));
oos.writeObject(new A("张三",23));
oos.close(); ObjectInputStream ois=new ObjectInputStream(new FileInputStream(new File("D:"+File.separator+"A.ser")));
A a=(A)ois.readObject();
ois.close();
System.out.println(a);
}
}

Serializable和transient应用示例