您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
在Java中,transient
关键字用于标记一个字段,使其不被序列化。当你将一个对象序列化时,transient
修饰的字段不会被保存到序列化流中,因此在反序列化后,这些字段的值会恢复为默认值(例如,对于数值类型,默认值为0或0.0;对于布尔类型,默认值为false;对于引用类型,默认值为null)。
你可以在Java类中使用transient
关键字来修饰字段,以防止它们被序列化。以下是一个简单的示例:
import java.io.*;
public class Person implements Serializable {
private String name;
private int age;
private transient String password; // 这个字段不会被序列化
public Person(String name, int age, String password) {
this.name = name;
this.age = age;
this.password = password;
}
@Override
public String toString() {
return "Person{" +
"name='" + name + '\'' +
", age=" + age +
", password='" + password + '\'' +
'}';
}
}
public class Main {
public static void main(String[] args) throws IOException, ClassNotFoundException {
Person person = new Person("John", 30, "secret");
// 序列化
FileOutputStream fos = new FileOutputStream("person.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(person);
oos.close();
// 反序列化
FileInputStream fis = new FileInputStream("person.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
Person deserializedPerson = (Person) ois.readObject();
ois.close();
System.out.println(deserializedPerson); // 输出:Person{name='John', age=30, password='null'}
}
}
在这个示例中,Person
类实现了Serializable
接口,表示该类的对象可以被序列化。password
字段被标记为transient
,因此在序列化和反序列化过程中,它的值不会被保存和恢复。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。