作用
1,一旦变量被transient修饰,变量将不再是对象持久化的一部分,该变量内容在序列化后无法获得访问。
2,transient关键字只能修饰变量,而不能修饰方法和类。注意,本地变量是不能被transient关键字修饰的。变量如果是用户自定义类变量,则该类需要实现Serializable接口。
3,一个静态变量不管是否被transient修饰,均不能被序列化。
请看代码
//实体类(必须实现Serializable接口,才能被序列化) public class Resume implements Cloneable,Serializable{ private static final long serialVersionUID = 1L; private String name; private static String sex; transient private String age; private WorkExperience workExperience; public WorkExperience getWorkExperience() { return workExperience; } public void setWorkExperience(WorkExperience workExperience) { this.workExperience = workExperience; } 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; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public void dispaly(){ System.out.println("姓名:"+name+" 年龄:"+age+" 性别:"+sex); // System.out.println("工作经历:"+workExperience.getWorkDate()+" "+workExperience.getCompany()); } public Object clone(){ try { Resume resume = (Resume)super.clone(); return resume; }catch (Exception e){ return null; } } } public class MainTest2 { public static void main(String[] args){ try { // 序列化Resume Resume resume = new Resume(); resume.setName("哈哈"); resume.setSex("男"); resume.setAge("20"); resume.dispaly(); ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("D:\resume.txt")); outputStream.writeObject(resume); outputStream.close(); }catch (Exception e){ e.printStackTrace(); } } } //输出结果 姓名:哈哈 年龄:20 性别:男
反序列化
public class MainTest2 { public static void main(String[] args){ try { // 序列化Resume Resume resume = new Resume(); // resume.setName("哈哈"); // resume.setSex("男"); // resume.setAge("20"); // resume.dispaly(); // ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("D:\resume.txt")); // outputStream.writeObject(resume); // outputStream.close(); //改变sex(根据结果可见sex未被序列化,而是直接从内存中读取) resume.setSex("女"); //反序列化 ObjectInputStream inputStream = new ObjectInputStream(new FileInputStream("D:\resume.txt")); Resume resume1 = (Resume) inputStream.readObject(); resume1.dispaly(); }catch (Exception e){ e.printStackTrace(); } } } //结果 姓名:哈哈 年龄:null 性别:女
根据结果可知age字段被transient修饰未能序列化成功,而sex反序列化之前改变了值,所以标明也未被序列化。