被static和transient关键字修饰过的字段是不会被序列化和反序列化的
方式1:自定义序列化字段
Java:
实现Externalizable接口
public class User implements Externalizable {
private Long id;
private transient String statusName;
private Date createTime;
@Override
public void writeExternal(ObjectOutput out) throws IOException {
System.out.println("Externalizable.writeExternal(ObjectOutput out) is called");
out.writeLong(this.id);
out.writeUTF(this.statusName);
out.writeObject(this.createTime);
}
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
System.out.println("Externalizable.readExternal(ObjectInput in) is called");
this.id = in.readLong();
this.statusName = in.readUTF();
this.createTime = (Date) in.readObject();
}
}
kryo:
public class User implements KryoSerializable {
private Long id;
private transient String statusName;
private Date createTime;
@Override
public void write(Kryo kryo, Output out) {
out.writeLong(this.id);
out.writeString(this.statusName);
out.writeLong(this.createTime.getTime());
}
@Override
public void read(Kryo kryo, Input in) {
this.id = in.readLong();
this.statusName = in.readString();
this.createTime = new Date(in.readLong());
}
}
使用kryo注解@Optional可以不序列化该字段
@FieldSerializer.Optional(value = "createTime")
private Date createTime;
方式2:全局配置
kryo:
https://github.com/EsotericSoftware/kryo/pull/417/commits/8aae38d9bb4a67940006d84e5dc818329c698fd4
FieldSerializerConfig config;
config.setSerializeTransient(true);
CachedField[] fields = ArrayUtils.addAll(getFields(), getTransientFields());
fastjson:
启动类或@Baen注入的时候添加
JSON.DEFAULT_GENERATE_FEATURE = SerializerFeature.config(
JSON.DEFAULT_GENERATE_FEATURE,
SerializerFeature.SkipTransientField, false
);