定义
java语言的关键字,变量修饰符,如果用transient声明一个实例变量,当对象存储时,它的值不需要维持。换句话来说就是,用transient关键字标记的成员变量不参与序列化过程。
作用
Java的serialization提供了一种持久化对象实例的机制。当持久化对象时,可能有一个特殊的对象数据成员,我们不想用serialization机制来保存它。为了在一个特定对象的一个域上关闭serialization,可以在这个域前加上关键字transient。当一个对象被序列化的时候,transient型变量的值不包括在序列化的表示中,然而非transient型的变量是被包括进去的。
例子
新建一个User类,实现序列化接口
1 import java.io.Serializable; 2 3 public class User implements Serializable { 4 private static final long serialVersionUID = -1897102804742639482L; 5 6 private String userName; 7 private transient String password; 8 9 public User() { 10 } 11 12 public User(String userName, String password) { 13 this.userName = userName; 14 this.password = password; 15 } 16 17 public String getUserName() { 18 return userName; 19 } 20 21 public void setUserName(String userName) { 22 this.userName = userName; 23 } 24 25 public String getPassword() { 26 return password; 27 } 28 29 public void setPassword(String password) { 30 this.password = password; 31 } 32 33 @Override 34 public String toString() { 35 return "User [userName=" + userName + ", password=" + password + "]"; 36 } 37 38 @Override 39 public int hashCode() { 40 final int prime = 31; 41 int result = 1; 42 result = prime * result + ((userName == null) ? 0 : userName.hashCode()); 43 return result; 44 } 45 46 @Override 47 public boolean equals(Object obj) { 48 if (this == obj) 49 return true; 50 if (obj == null) 51 return false; 52 if (getClass() != obj.getClass()) 53 return false; 54 User other = (User) obj; 55 if (userName == null) { 56 if (other.userName != null) 57 return false; 58 } else if (!userName.equals(other.userName)) 59 return false; 60 return true; 61 } 62 63 }
测试类
1 import java.io.FileInputStream; 2 import java.io.FileOutputStream; 3 import java.io.IOException; 4 import java.io.ObjectInputStream; 5 import java.io.ObjectOutputStream; 6 7 public class TestTransient { 8 9 public static void main(String[] args) { 10 User user = new User(); 11 12 user.setUserName("zhangsan"); 13 user.setPassword("123"); 14 15 String fileName = "user.out"; 16 ObjectOutputStream oos = null; 17 try { 18 oos = new ObjectOutputStream(new FileOutputStream(fileName)); 19 oos.writeObject(user); 20 oos.flush(); 21 } catch (IOException e) { 22 e.printStackTrace(); 23 } finally { 24 try { 25 oos.close(); 26 } catch (IOException e) { 27 e.printStackTrace(); 28 } 29 } 30 31 32 User newUser = null; 33 ObjectInputStream ois = null; 34 try { 35 ois = new ObjectInputStream(new FileInputStream(fileName)); 36 newUser = (User) ois.readObject(); 37 38 System.out.println(newUser.toString()); 39 } catch (IOException e) { 40 e.printStackTrace(); 41 } catch (ClassNotFoundException e) { 42 e.printStackTrace(); 43 } finally { 44 try { 45 ois.close(); 46 } catch (IOException e) { 47 e.printStackTrace(); 48 } 49 } 50 } 51 52 }
控制台打印:
User [userName=zhangsan, password=null]
注意:passsword为null