transient关键字的用法

来源:互联网 发布:模块度 复杂网络 编辑:程序博客网 时间:2024/06/04 20:48

    transient关键字只能用来修饰字段,表明这个字段不需要被序列化。简单的看下面的例子,就明白了其用法了:

        import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
//Serializable接口没有任何需要实现的方法,实现这个接口是为了声明这个对象可以序列化
public class TransientDemo implements Serializable{
 private static final long serialVersionUID = 1L;
 String name;
 //用了transient这个关键字,这个字段就不会被序列化了
 transient String password;
 public TransientDemo(String name, String password) {
  this.name = name;
  this.password = password;
 }
 @Override
 public String toString() {
  return name + ":" + password;
 }
 public static void main(String[] args) {
  TransientDemo td = new TransientDemo("Yinyan", "love");
  try{
   ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("log.txt"));
   oos.writeObject(td);
   oos.close();
  }catch(Exception e){
   e.printStackTrace();
  }
 
  try{
   ObjectInputStream ois = new ObjectInputStream(new FileInputStream("log.txt"));
   TransientDemo td2 = (TransientDemo) ois.readObject();
   System.out.println(td2);
  }catch(Exception e){
   e.printStackTrace();
  }
 }
}
输出结果为:
    这段代码创建了一个对象,然后序列化这个对象,保存到log.txt这个文件中,在从log.txt这个文件读取出对象。我们发现name字段内容正常,password字段却为空。这是因为,保底保存密码风险很大,所以我们把password字段定义为不需要序列化。
     另外需要说明一点,如果类实现的是Externalizable这个接口,在writeExternal方法内部手动序列化password字段的话,transient 这个关键字是不会起作用的。

0 0
原创粉丝点击