在对象序列化的时候,有些变量比如密码等等,你需希望他去序列化,否则别人就可以通过字节流来回复数据得到你的private的数据,这样是一个很危险的问题,下面使用关键字Transient 来解决这个问题,他的意思就是不需要虚拟机去序列化这个变量,我会自己去处理.

注意了,这里是仅仅在对象序列化的时候,我有讲过,可以看一下哈。

package com.bird.thinking;

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;

/**
 * @use  transient关键字实现对指定变量的非序列化
 * @author Bird
 *
 */
public class Login implements Serializable{
	private Date date = new Date();
	private String username;
	private transient String password;//注意transient关键字的运用
	
	public Login(String name, String pwd){
		username = name;
		password = pwd;
	}
	
	public String toString(){
		return "Login info: \n    username:  " + username + "\n date:  " + date +  "\n  password " + password;
	}
	
	public static void main(String [] args) throws Exception{
		Login a = new Login("Bird", "Hehe");
		System.out.println("Login a = a" + a);
		ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream("d://login.out"));
		o.writeObject(a);
		o.close();
		Thread.sleep(500);
		//Now  Get Back
		ObjectInputStream in = new ObjectInputStream(new FileInputStream("d://login.out"));  
		System.out.println("recovering  object  at "  + new Date());
		a = (Login)in.readObject();
		System.out.println("Login a = " + a);
	}
}

运行结果为:

Login a = aLogin info: 
username:  Bird
date:  Sun Oct 23 15:38:51 CST 2011
password Hehe
recovering  object  at Sun Oct 23 15:38:52 CST 2011
Login a = Login info: 
username:  Bird
date:  Sun Oct 23 15:38:51 CST 2011
password null


Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐