ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# Java transient 关键字 ## transient 关键字 transient 功能: 当对象被序列化时(写入字节序列到目标文件)时,transient阻止实例中那些用此关键字声明的变量持久化;当对象被反序列化时(从源文件读取字节序列进行重构),这样的实例变量值不会被持久化和恢复。 ~~~ public class UserTest implements Serializable { private String name; private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserTest{" + "name='" + name + '\'' + ", password='" + password + '\'' + '}'; } } ~~~ ~~~ public static void main(String[] args) throws IOException, ClassNotFoundException { UserTest userTest = new UserTest(); userTest.setName("xiaoming"); userTest.setPassword("123456"); System.out.println(userTest.toString()); String relativelyPath=System.getProperty("user.dir"); ObjectOutputStream os = new ObjectOutputStream( new FileOutputStream(relativelyPath + "/src/main/resources/user.txt")); //写入文件 os.writeObject(userTest); os.flush(); os.close(); //读入文件 ObjectInputStream is = new ObjectInputStream(new FileInputStream( relativelyPath + "/src/main/resources/user.txt")); //读入文件 userTest = (UserTest) is.readObject(); System.out.println(userTest.toString()); is.close(); } ~~~ ~~~ //输出 UserTest{name='xiaoming', password='123456'} UserTest{name='xiaoming', password='123456'} ~~~ 上述是正常的序列化写入文件,然后读取文件的逻辑。 在使用 transient 后: ~~~javascript public class UserTest implements Serializable { private String name; //注意这里的 transient transient private String password; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "UserTest{" + "name='" + name + '\'' + ", password='" + password + '\'' + '}'; } } ~~~ 然后再运行程序,输出结果如下: ~~~ UserTest{name='xiaoming', password='123456'} UserTest{name='xiaoming', password='null'} ~~~ 可以看到 password 在被 transient 修饰后,没有序列化和反序列化 * * * ## 总结 * 变量在被 transient 修饰后,变量将不再是对象持久化时的一部分,即变量内容不再被序列化 * transient 只能修饰变量 * 静态变量不管是否被 transient 修饰,均不能被序列化