MadGoat's Blog

导航

反序列化对象时处理package和serialVersionUID不一致

import java.io.*;
import java.lang.reflect.Field;

public class MyObjectInputStream extends ObjectInputStream {

    protected MyObjectInputStream() throws IOException, SecurityException {
        super();
    }

    public MyObjectInputStream(InputStream arg0) throws IOException {
        super(arg0);
    }


    @Override
    protected Class<?> resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException {
        try {
            System.out.println(">>>" + desc.getName());
            if (desc.getName().contains("MyList")) {//LimitQueue
                return Class.forName(Comm.UID1);//Comm.UID
            } else if (desc.getName().contains("MyObject")) {//MBar
                return Class.forName(Comm.UID2);//Comm.UID
            } else {
                return Class.forName(desc.getName());
            }
        } catch (ClassNotFoundException ex) {
            ex.printStackTrace();
            System.out.println(ex);
        }

        return super.resolveClass(desc);
    }

    @Override
    protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException {
        ObjectStreamClass desc = super.readClassDescriptor();
        System.out.println(">>>desc>>>" + desc);
//        desc.getClass().getDeclaredField()
        if ((desc.getName().contains("MyList") || desc.getName().contains("MyObject")) && desc.getSerialVersionUID() != 1) {
            Field field = null;
            try {
                field = desc.getClass().getDeclaredField("suid");
                field.setAccessible(true);
                field.set(desc, 1L);
                System.out.println("change desc:" + desc);
//        desc.suid=1l;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return desc;
    }


}

  先记录下代码,最近需要处理一个反序列化对象,package名称变更的问题,package的变更导致无法反序列化读取数据,通过继承ObjectInputStream,重写resolveClass,来欺骗下编译器,连锁反应是,发现package变更后,serialVersionUID也变更了,而之前没显式指定,又是一个坑.

阅读源码后,修改readClassDescriptor方法里的获取类描述的数据,再次欺骗下,搞定,记录下.for 老Y同志 哈.

posted on 2020-03-14 10:58  MadGoat  阅读(758)  评论(0编辑  收藏  举报