transient关键字,表明一个属性是临时的,如果Class类实现了 Serializable接口,被transient修饰的属性不会被持久化!!!
代码验证:
public class TransientDemo implements Serializable {
private static final long serialVersionUID = 1415782474432670389L;
private String name;
private transient String sex;
public TransientDemo() {
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
@Override
public String toString() {
return "TransientDemo{" +
"name='" + name + '\'' +
", sex='" + sex + '\'' +
'}';
}
public static void main(String[] args) throws IOException {
String path = "D:"+ File.separator+"transientDemo.txt";
File file = new File(path);
TransientDemo transientDemo = new TransientDemo();
transientDemo.setName("张三");
transientDemo.setSex("保密:女");
System.out.println("before: " + transientDemo);
ObjectOutputStream output = null;
try {
output = new ObjectOutputStream(new FileOutputStream(file));
output.writeObject(transientDemo);
} catch (IOException e) {
e.printStackTrace();
}finally {
output.flush();
output.close();
}
ObjectInput input = null;
try {
input = new ObjectInputStream(new FileInputStream(file));
TransientDemo demo = (TransientDemo) input.readObject();
System.out.println("after: " + demo );
} catch (IOException e) {
e.printStackTrace();
}catch (ClassNotFoundException ex){
ex.printStackTrace();
}finally {
input.close();
}
/* output----------------------------
before: TransientDemo{name='张三', sex='保密:女'}
after: TransientDemo{name='张三', sex='null'}
*/
}
}