zzh

zzh

Can Jdk8 static variables be serialized?

First of all, static variables cannot be serialized.

Verification:
  • Entity class:
@Data
public class SysRole implements Serializable {

    // Role ID
    private BigInteger id;
    // Role name
    private String name;
    // Role code to determine if it is a system administrator
    private String code;
    // Role description
    private String description;
    // Creator ID
    private BigInteger createBy;
    // Modifier ID
    private BigInteger modifyBy;
    // Status: 0 - disabled, 1 - enabled
    private int status;
    // Creation time
    private Date created;
    // Last update time
    private Date lastUpdateTime;
    
    private static String remark;
    
    public void setRemark(String remark){
        this.remark = remark;
    }
    
    public String getRemark(){
        return remark;
    }
}
  • Serialization:
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);
  • Deserialization:
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());
  • Result:

image

  • Exception
    Deserialization code:
---------Added code------------
SysRole sysRole = new SysRole();
sysRole.setRemark("what");
---------Added code------------

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());

Result:

image

Reason analysis:

image
In other words, static variables are stored on the class object. Therefore, after sysRole sets the remark, it will be saved on the class object for subsequent use by SysRole objects.

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.