java transient 知识点学习

今天看源码的时候看到这个关键字,完全没见过,不懂。好吧!学习一下。

 

我们都知道实现了Serilizable接口的类,便可以序列化,那么其中某些成员变量不想被序列化怎么办?就是利用transient这个关键字来实现。废话不多说,上例子。

 1 import java.io.FileInputStream;
 2 import java.io.FileNotFoundException;
 3 import java.io.FileOutputStream;
 4 import java.io.IOException;
 5 import java.io.ObjectInputStream;
 6 import java.io.ObjectOutputStream;
 7 
 8 public class TransientTest {
 9     
10     public static void main(String[] args) {
11         
12         User user = new User();
13         user.setUsername("lee");
14         user.setPasswd("123456");
15         
16         System.out.println("read before Serializable: ");
17         System.out.println("username: " + user.getUsername());
18         System.err.println("password: " + user.getPasswd());
19         
20         try {
21             ObjectOutputStream os = new ObjectOutputStream(
22                     new FileOutputStream("C:/f_work/user.txt"));
23             os.writeObject(user);
24             os.flush();
25             os.close();
26         } catch (FileNotFoundException e) {
27             e.printStackTrace();
28         } catch (IOException e) {
29             e.printStackTrace();
30         }
31         try {
32             ObjectInputStream is = new ObjectInputStream(new FileInputStream(
33                     "C:/f_work/user.txt"));
34             user = (User) is.readObject();
35             is.close();
36             
37             System.out.println("\nread after Serializable: ");
38             System.out.println("username: " + user.getUsername());
39             System.err.println("password: " + user.getPasswd());
40             
41         } catch (FileNotFoundException e) {
42             e.printStackTrace();
43         } catch (IOException e) {
44             e.printStackTrace();
45         } catch (ClassNotFoundException e) {
46             e.printStackTrace();
47         }
48     }
49 }
50 
51 
52 import java.io.Serializable;
53 
54 class User implements Serializable {
55     private static final long serialVersionUID = 8294180014912103005L;  
56     
57     private String username;
58     private transient String passwd;
59     
60     public String getUsername() {
61         return username;
62     }
63     
64     public void setUsername(String username) {
65         this.username = username;
66     }
67     
68     public String getPasswd() {
69         return passwd;
70     }
71     
72     public void setPasswd(String passwd) {
73         this.passwd = passwd;
74     }
75 
76 }

运行结果:

read before Serializable:
password: 123456
username: lee

read after Serializable:
username: lee
password: null

null说明没有取到信息。

posted @ 2017-11-05 22:53  Mr.袋鼠  阅读(186)  评论(0编辑  收藏  举报