面试题答案
一键面试1. Transient关键字在对象序列化场景下的作用
在Java中,当一个对象需要被序列化(即将对象转换为字节流以便存储或传输)时,默认情况下,对象的所有成员变量都会被序列化。然而,如果一个成员变量被transient
关键字修饰,那么在序列化过程中,该变量将不会被包含在序列化的字节流中。这意味着当对象被反序列化时,被transient
修饰的变量将被赋予其类型的默认值(例如,int
类型为0,Object
类型为null
)。
2. 举例说明使用Transient关键字修饰成员变量前后,对象序列化结果的不同
import java.io.*;
class User implements Serializable {
private String name;
private transient String password;
public User(String name, String password) {
this.name = name;
this.password = password;
}
public String getName() {
return name;
}
public String getPassword() {
return password;
}
}
public class TransientExample {
public static void main(String[] args) {
User user = new User("John", "secretPassword");
// 序列化对象
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("user.ser"))) {
oos.writeObject(user);
} catch (IOException e) {
e.printStackTrace();
}
// 反序列化对象
User deserializedUser = null;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("user.ser"))) {
deserializedUser = (User) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
if (deserializedUser != null) {
System.out.println("Deserialized Name: " + deserializedUser.getName());
System.out.println("Deserialized Password: " + deserializedUser.getPassword());
}
}
}
- 未使用
transient
修饰password
变量时:如果password
变量没有被transient
修饰,在序列化和反序列化后,password
的值仍然是"secretPassword"
。 - 使用
transient
修饰password
变量时:从上述代码的输出可以看到,反序列化后password
的值为null
,因为password
被transient
修饰,在序列化时未被保存,反序列化时被赋予了String
类型的默认值null
。这在保护敏感信息(如密码)时非常有用,避免将敏感信息存储在序列化文件或通过网络传输。