transient关键字的作用是在对象的序列化中体现的,如果一个类的变量被transient修饰,那么这个对象在序列化的过程中,不会序列化这个变量。在反序列的过程中,也不会反序列这个变量。
1 @Data 2 public class User implements Serializable{ 3 private transient String name; 4 private String desc; 5 } 6 7 @Test 8 public void fun1() { 9 User user = new User(); 10 user.setDesc("sss"); 11 user.setName("zhangsan"); 12 System.out.println("序列化之前 "+user.toString()); 13 14 String path = "D:/test.txt"; 15 try { 16 ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(path)); 17 outputStream.writeObject(user); 18 19 ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(path)); 20 user = (User) objectInputStream.readObject(); 21 System.out.println("序列化之后 "+user.toString()); 22 } catch (IOException e) { 23 e.printStackTrace(); 24 } catch (ClassNotFoundException e) { 25 e.printStackTrace(); 26 } 27 }
输出结果: 序列化之前 User(name=zhangsan, desc=sss) 序列化之后 User(name=null, desc=sss)