首页 > 代码库 > Transient关键字的作用
Transient关键字的作用
在对象序列化的时候,有些变量不需要序列化,比如密码等,可以使用transient关键字来解决这个问题,transient修饰的变量不会被序列化。
例子:
1 import java.io.*; 2 import java.util.Date; 3
4 5 /** 6 * Created by leiqiang on 2014/7/25. 7 */ 8 public class TransientTest implements Serializable{ 9 private Date date = new Date();10 private String username;11 private transient String password;12 13 public TransientTest(String username,String password){14 this.username=username;15 this.password=password;16 }17 18 @Override19 public String toString() {20 return new Date()+" username "+username+" : password "+password;21 }22 23 public static void main(String[] args) throws Exception{24 TransientTest transientTest = new TransientTest("lei","1234");25 System.out.println(transientTest);26 FileOutputStream fileOutputStream = new FileOutputStream("d:/Cache/TransientTest.txt");27 ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);28 objectOutputStream.writeObject(transientTest);29 objectOutputStream.close();30 Thread.sleep(2000);31 FileInputStream fileInputStream = new FileInputStream("d:/Cache/TransientTest.txt");32 ObjectInputStream objectInputStream = new ObjectInputStream(fileInputStream);33 transientTest = (TransientTest)objectInputStream.readObject();34 System.out.println(transientTest);35 }36 }
运行结果:
1 Fri Jul 25 13:56:13 CST 2014 username lei : password 12342 Fri Jul 25 13:56:15 CST 2014 username lei : password null
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。