美文网首页
序列化与反序列化

序列化与反序列化

作者: 采药僧 | 来源:发表于2019-10-29 19:05 被阅读0次

    场景:项目中,将对象序列化,base64编码,存入到redis缓存中。使用时在反序列化取出来。
    问题:对象增加新的基本类型属性long类型。对于使用没有该属性的对象序列化的结果能否被反序列化初始这个属性。

    基本类型

    1、序列初始化时,将手机发送时间sendTime相关属性以及下文测试方法的步骤2注释掉。
    2、运行测试样例,生成sms.txt文件。
    3、取消注释,将测试方法的步骤1注释掉。
    4、运行测试样例,看控制台打印信息。

    package study.java.Serializable;
    
    import java.io.Serializable;
    
    public class MessageValue implements Serializable {
    
        private static final long serialVersionUID = -4387708091987654321L;
        // 手机短信验证码
        private String code;
    
        // 手机短信发送时间
        private long sendTime;
    
        //验证次数
        private int validateCount;
    
        public MessageValue(){
    
        }
    
        public String getCode() {
            return code;
        }
    
        public void setCode(String code) {
            this.code = code;
        }
    
        public long getSendTime() {
            return sendTime;
        }
    
        public void setSendTime(long sendTime) {
            this.sendTime = sendTime;
        }
    
    
        public int getValidateCount() {
            return validateCount;
        }
    
        public void setValidateCount(int validateCount) {
            this.validateCount = validateCount;
        }
    
    }
    
    
    package study.java.Serializable;
    
    import java.io.*;
    
    public class SerializableTest  {
        public static void main(String[] args) throws Exception {
           //步骤1
            serializeMessageValue();
            //步骤2
            MessageValue messageValue = deserializeMessageValue();
            StringBuilder sb = new StringBuilder();
            System.out.println(messageValue.getLastSendTime());
    
        }
    
        /**
         * 序列化
         */
        private static void serializeMessageValue() throws IOException {
            MessageValue messageValue=new MessageValue();
            messageValue.setCode("123456");
            messageValue.setValidateCount(1);
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(new File("d:/sms.txt")));
            oos.writeObject(messageValue);
            System.out.println("对象序列化成功!");
            oos.close();
        }
    
        /**
         * 反序列化
         */
        private static MessageValue deserializeMessageValue() throws Exception {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("d:/sms.txt")));
            MessageValue mess = (MessageValue) ois.readObject();
            System.out.println("对象反序列化成功!");
            return mess;
        }
    }
    
    

    结论

    打印初始对象long为0。证明可以得到该属性,并且该属性被初始为0,不会产生异常。

    注:自己设置一个 serialVersionUID,否则jvm自动分配,报非法异常。

    相关文章

      网友评论

          本文标题:序列化与反序列化

          本文链接:https://www.haomeiwen.com/subject/kicgvctx.html