transient 关键字的作用
transient可以修饰在成员属性上, 目的是让其不序列化
定义一个对象
public class User implements Serializable {
private String name;
private transient int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
编写测试类
User user = new User();
user.setName("kangping");
user.setAge(18);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
objectOutputStream.writeObject(user);
byte[] bytes = byteArrayOutputStream.toByteArray();
System.out.println(bytes.length);
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream);
User object = (User) objectInputStream.readObject();
System.out.println(object);
逻辑是将user对象序列化到内存到数组当中,然后反序列化,然后看结果
结果:
发现当用transient修饰完字段后,设置了18当age字段没有被序列化出来(0是默认值)
使用后怎么又怎么序列化
我们在user类当中添加2个方法
private void writeObject(ObjectOutputStream objectOutputStream) throws IOException {
objectOutputStream.defaultWriteObject();
objectOutputStream.writeInt(age);
}
private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
objectInputStream.defaultReadObject();
int age = objectInputStream.readInt();
this.age = age;
}
我们看结果:
结果是18被序列化出来了。writeObject和readObject是jvm 层面反射去调用的。writeObject编写序列化的逻辑,readObject编写反序列化的逻辑