java中的transient

来源:互联网 发布:网吧无限上网软件 编辑:程序博客网 时间:2024/05/17 04:51

被声明为transient的属性,在序列化保存时是不会被保存的,比如密码这类信息,为了安全性,在序列化存储对象时不需要保存,则可以把密码声明为transient.

如下是transient的例子

保存对象前输出:saved User:cn.learn.test.User@1c39a2d->username=googlepassword=aaabbb111

从文件中重新读取该对象,输出:readed User:cn.learn.test.User@1f14ceb->username=googlepassword=null

可见,声明为transient后的password属性在保存时并没有写入文件,重新读取出user对象时password是null

 

package cn.learn.test;

import java.io.File;
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;

public class TestTransient {

 /**
  * @param args
  */
 public static void main(String[] args) {
  // TODO Auto-generated method stub
  User user = new User();
  try {
   //序列化保存Object到文件中
   ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream(new File("user.do")));
   objectOutputStream.writeObject(user);
   System.out.println("saved User:"+user);
   Thread.currentThread().sleep(5*1000);
   //从文件中读取序列化的对象
   ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("user.do"));
   Object obj = objectInputStream.readObject();
   if(obj instanceof User){
    User user2 = (User)obj;
    System.out.println("readed User:"+user2);
   }else {
    System.out.println("the obj readed from ObjectInputStream is not a User!");
   }
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }catch (Exception e) {
   // TODO: handle exception
   e.printStackTrace();
  }
 }

}

//该类的对象将被序列化,但是声明为transient的属相在序列化存储这个对象时不被存储
class User implements Serializable{
 
 private String username="google";
 //声明为transient,表示该属性在序列化存储这个对象时不被存储
 private transient String password="aaabbb111";
 @Override
 public String toString() {
  // TODO Auto-generated method stub
  return super.toString()+"->username="+username+"password="+password;
 }
 @Override
 protected void finalize() throws Throwable {
  // TODO Auto-generated method stub
  super.finalize();
  System.out.println("finalize:"+username);
 } 
}

原创粉丝点击