java序列化和反序列化 以及transient的含义

======================================Emoloyee实体类
package JavaHeigth.serializableTest;
import java.io.Serializable;

public class Employee implements Serializable{
private static final long serialVersionUID = 3593458869057048152L;
public String name ;
public String address;
public [color=red]transient [/color]int SSN; //不可序列化状态 瞬态
public int number;
public void mailCheck(){
System.out.println("Mailing a check to " +name +" "+address );
}
}
======================================序列化
package JavaHeigth.serializableTest;

import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

public class SerializeDemo {
public static void main(String[] args) {
Employee e = new Employee();
e.name="kaige";
e.address="北京海淀";
e.SSN=112233;
e.number=101;
try {
FileOutputStream fos = new FileOutputStream("f://employee.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(e);
oos.close();
fos.close();
System.out.println("序列化保存在f://employee.ser中");
} catch (Exception e2) {
// TODO: handle exception
System.out.println("异常");
e2.printStackTrace();
}

}
}

=============================反序列化
package JavaHeigth.serializableTest;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class DeserializeDemo {
public static void main(String [] args)
{
Employee e = null;
try
{
FileInputStream fileIn = new FileInputStream("f://employee.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
e = (Employee) in.readObject();
in.close();
fileIn.close();
}catch(IOException i)
{
i.printStackTrace();
return;
}catch(ClassNotFoundException c)
{
System.out.println("Employee class not found");
c.printStackTrace();
return;
}
System.out.println("Deserialized Employee...");
System.out.println("Name: " + e.name);
System.out.println("Address: " + e.address);
System.out.println("SSN: " + e.SSN);
System.out.println("Number: " + e.number);
}
}

[color=red]SSN=0;原因是transient 变量不能被序列化[/color]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值