Outline
In Java, a class can implement the Serializable interface objects of this class can be serialized, this sequence mode provides a lot of convenience for developers, we do not have to care about the specific sequence of the process, as long as the class implements Serializable interfaces, all the properties of this class are automatically serialized. But sometimes we need to let some of the properties of the class are not serialized, such as password information, for security reasons, do not want to be transmitted or persistence in the network to the local operation. As long precede the corresponding attribute
transient
keywords, you can achieve some of the properties are not serialized, the life cycle of the property exists only in the memory of the caller will not be written to disk persistence.
The use of transient
public class TransientTest {
public static void main(String[] args) { User user = new User(); user.setUsername("Github"); user.setPassword("123456"); System.out.println("read before Serializable: "); System.out.println("username: " + user.getUsername()); System.err.println("password: " + user.getPassword()); try { ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("user.txt")); os.writeObject(user); // 将User对象写进文件 os.flush(); os.close(); } catch (IOException e) { e.printStackTrace(); } try { ObjectInputStream is = new ObjectInputStream(new FileInputStream("user.txt")); user = (User) is.readObject(); // 从流中读取User的数据 is.close(); System.out.println("\nread after Serializable: "); System.out.println("username: " + user.getUsername()); System.err.println("password: " + user.getPassword()); } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); } } } public class User implements Serializable { private static final long serialVersionUID = 1234567890L; private String username; private transient String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this