- transient关键字,防止关键对象的数据被序列化。
import java.io.*;
/**
* Created by L on 2014/5/29.
*/
class MyTransient implements Serializable{
String v1;
transient String v2;
static String v3;
MyTransient(){
v1 = "v1";
v2 = "v2";
v3 = "v3";
}
@Override
public String toString(){
System.out.println("v1 - " + v1 + "; v2 - " + v2 + "; v3 - " + v3);
return "v1 - " + v1 + "; v2 - " + v2 + "; v3 - " + v3;
}
void mkSerialization(Object ob, String file){
try {
ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
oos.writeObject(ob);
oos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Object readSerialization(String file){
Object ob = null;
try {
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));
ob = ois.readObject();
ois.close();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return ob;
}
}
class main{
public static void main(String[] args){
String file = "./mytransient3";
MyTransient mt = new MyTransient();
mt.mkSerialization(mt, file);
MyTransient ob = (MyTransient) mt.readSerialization(file);
mt.toString();
ob.toString();
}
}
文件序列化前后,transient关键字标注的变量v2有值,为空。防止重要数据被序列化后被盗取其中数据。