Transient关键字在Java对象序列化中的作用

               

在对象序列化的时候,有些变量比如密码等等,你需希望他去序列化,否则别人就可以通过字节流来回复数据得到你的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 Serializableprivate 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:  Birddate:  Sun Oct 23 15:38:51 CST 2011password Heherecovering  object  at Sun Oct 23 15:38:52 CST 2011Login a = Login info: username:  Birddate:  Sun Oct 23 15:38:51 CST 2011password null


           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

猜你喜欢

转载自blog.csdn.net/qq_43679366/article/details/86611773