面试题答案
一键面试在Java中,若对象的某些字段不想被序列化,可以使用 transient
关键字修饰这些字段。
示例代码如下:
import java.io.*;
class User implements Serializable {
private String name;
// 不想被序列化的字段
private transient int password;
public User(String name, int password) {
this.name = name;
this.password = password;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", password=" + password +
'}';
}
}
public class SerializationExample {
public static void main(String[] args) {
User user = new User("John", 123456);
// 序列化
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 User: " + deserializedUser);
}
}
}
在上述代码中,User
类实现了 Serializable
接口,其中 password
字段被 transient
修饰,在序列化和反序列化过程中,password
字段的值不会被保存和恢复。