今天看源码的时候看到这个关键字,完全没见过,不懂。好吧!学习一下。
我们都知道实现了Serilizable接口的类,便可以序列化,那么其中某些成员变量不想被序列化怎么办?就是利用transient这个关键字来实现。废话不多说,上例子。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class TransientTest { public static void main(String[] args) { User user = new User();
user.setUsername("lee");
user.setPasswd("123456"); System.out.println("read before Serializable: ");
System.out.println("username: " + user.getUsername());
System.err.println("password: " + user.getPasswd()); try {
ObjectOutputStream os = new ObjectOutputStream(
new FileOutputStream("C:/f_work/user.txt"));
os.writeObject(user);
os.flush();
os.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
ObjectInputStream is = new ObjectInputStream(new FileInputStream(
"C:/f_work/user.txt"));
user = (User) is.readObject();
is.close(); System.out.println("\nread after Serializable: ");
System.out.println("username: " + user.getUsername());
System.err.println("password: " + user.getPasswd()); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} import java.io.Serializable; class User implements Serializable {
private static final long serialVersionUID = 8294180014912103005L; private String username;
private transient String passwd; public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPasswd() {
return passwd;
} public void setPasswd(String passwd) {
this.passwd = passwd;
} }
运行结果:
read before Serializable:
password: 123456
username: lee
read after Serializable:
username: lee
password: null
null说明没有取到信息。