面试题--对象序列持久化

今天闲下来,想到一道面试题,
对象A实现了序列化接口, 
对象B为A的实例变量,未序列化,当把A对象持久化到文件中时,就会抛出NotSerializableException

也就是说,要持久化对象,或传输时,需要对其所引用的实例进行序列化,

public class NotSerializ {
	public String name = "aaaa";
}


public class MySerializ implements Serializable{

	private static final long serialVersionUID = -7918349215312458095L;
	public NotSerializ  not;
	public long num = 9;
	
	public static void main(String[] args) {
		MySerializ mySerializ = new MySerializ();
		mySerializ.doSerializ();
		mySerializ.readSerializ();
	}

	private void readSerializ() {
		File file = new File("text.txt");	
		try {
			FileInputStream out  = new FileInputStream(file);
			ObjectInputStream  oin = new ObjectInputStream (out);
			Object o = oin.readObject();
			
			System.out.println(((MySerializ)o).not.name);
			System.out.println(((MySerializ)o).num);
			oin.close();		
		} catch (Exception e) {
			e.printStackTrace();
		}	
	}

	private void doSerializ() {
		MySerializ o = new MySerializ();
		o.num = 3;
		o.not = new NotSerializ();
		
		File file = new File("text.txt");	 
		try {
			FileOutputStream out  = new FileOutputStream(file);
			ObjectOutputStream  oput  = new ObjectOutputStream (out);
			oput.writeObject(o);
			oput.close();		
		} catch (Exception e) {
			e.printStackTrace();
		}	
		
	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值