zzh

zzh

Jdk8 static变量是否可以序列化

先上结论,static 变量无法序列化。

验证:
  • 实体类:
@Data
public class SysRole implements Serializable {

    // 角色id
    private BigInteger id;
    // 角色名词
    private String name;
    // 角色代码 可以判断是否是系统管理员
    private String code;
    // 角色描述
    private String description;
    // 创建者id
    private BigInteger createBy;
    // 修改者id
    private BigInteger modifyBy;
    // 状态:0:禁用 1:启用
    private int status;
    // 创建时间
    private Date created;
    // 修改时间
    private Date lastUpdateTime;
    
    private static String remark;
    
    public void setRemark(String remark){
        this.remark = remark;
    }
    
    public String getRemark(){
        return remark;
    }
}
  • 序列化:
SysRole sysRole = new SysRole();
sysRole.setName("213");
sysRole.setCreated(new Date());
sysRole.setCode("132");
System.out.println(sysRole.toString());
sysRole.setRemark("how");
ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("d:/user.txt"));
objectOutputStream.writeObject(sysRole);
  • 反序列化:
ObjectInputStream objectInputStream = null;
try {
    objectInputStream = new ObjectInputStream(new FileInputStream("d:/user.txt"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
SysRole readObject = null;
try {
    readObject = (SysRole)objectInputStream.readObject();
} catch (IOException e) {
    throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
    throw new RuntimeException(e);
}
System.out.println(readObject.getRemark());
  • 结果:

image

  • 例外
    反序列化代码:
---------新增代码------------
SysRole sysRole = new SysRole();
sysRole.setRemark("what");
---------新增代码------------

ObjectInputStream objectInputStream = null;
try {
    objectInputStream = new ObjectInputStream(new FileInputStream("d:/user.txt"));
} catch (IOException e) {
    throw new RuntimeException(e);
}
SysRole readObject = null;
try {
    readObject = (SysRole)objectInputStream.readObject();
} catch (IOException e) {
    throw new RuntimeException(e);
} catch (ClassNotFoundException e) {
    throw new RuntimeException(e);
}
System.out.println(readObject.getRemark());

结果:

image

原因分析:

image
也就是说 static 变量会放在 class 对象上,因此 sysRole 设置了 remark 以后会保存在 class 对象上供后续的 SysRole 对象使用。

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。