代码如下:

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; public class MyTest implements Serializable{ private static final long serialVersionUID = 1L;
private String name="SheepMu";
private transient int age=24;
private Book book=new Book("我是一本书");
public static void main(String[] args) {
try
{
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("my.out"));//输出流保存的文件名为 my.out ;ObjectOutputStream能把Object输出成Byte流
MyTest myTest=new MyTest();
oos.writeObject(myTest);
oos.flush(); //缓冲流
oos.close(); //关闭流
} catch (FileNotFoundException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}
System.out.println("success");
fan();
}
public static void fan()//反序列的过程
{
ObjectInputStream oin = null;//局部变量必须要初始化
try
{
oin = new ObjectInputStream(new FileInputStream("my.out"));
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
} catch (IOException e1)
{
e1.printStackTrace();
}
MyTest mts = null;
try {
mts = (MyTest ) oin.readObject();//由Object对象向下转型为MyTest对象
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("name="+mts.name);
System.out.println("age="+mts.age);
System.out.println("书"+mts.book.getBookname());
}
}

意思就是:

book类省略;

如果不用transient 关键字 修饰的话,每一个  测试类中的属性都会初始化,在返序列化中可以拿到值

(如果在成员变量中出现自身定义的类型,则该类型必须实现serilizable接口)

如果用transient 修饰的话,则拿到的值为空甚至出现空指针

05-11 17:49