在对象序列化的时候,有些变量比如密码等等,你需希望他去序列化,否则别人就可以通过字节流来回复数据得到你的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