欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

android 实现序列化和反序列化是不同包下相同类的解决方案

程序员文章站 2022-06-20 20:25:12
...

将ObjectInputStream重写,防止报java.lang.ClassCastException错误,重写如下,里面要指定需要加载的那个类。

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectStreamClass;

public class ObjectInputStreamWithLoader extends ObjectInputStream {


    public ObjectInputStreamWithLoader(InputStream in) throws IOException {
        super(in);
    }

    /**
     * Use the given ClassLoader rather than using the system class
     */
    @SuppressWarnings("rawtypes")
    protected Class resolveClass(ObjectStreamClass classDesc) throws IOException, ClassNotFoundException {
        return com.example.testlivedata.model.Person.class;//此处是指定加载的类
    }

}

序列化和反序列化代码如下:

bt1.setOnClickListener {

            var person = Person();
            person.age = 11
            person.id = 110
            person.name = "张三"
            var objectOutputStream = ObjectOutputStream(FileOutputStream(cacheDir.path+"/p.text"))
            objectOutputStream.writeObject(person)
            objectOutputStream.close()
        }

        bt2.setOnClickListener {

            val urls = arrayOfNulls<URL>(0)

            val classLoader =
                URLClassLoader(urls, ClassLoader.getSystemClassLoader())
//            var objectInputStream = ObjectInputStream(FileInputStream(cacheDir.path+"/p.text"))
//            var person = objectInputStream.readObject() as com.example.testlivedata.model.Person
//            Log.e("sssssssssssss", person.toString())
            var objectInputStreamWithLoader =
                ObjectInputStreamWithLoader(FileInputStream(cacheDir.path + "/p.text"))
            var person =
                objectInputStreamWithLoader.readObject() as com.example.testlivedata.model.Person
            Log.e("sssssss",person.toString())
        }

Person类如下,记得需要写serialVersionUID,并且两边要一致。

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = -4211449776975163975L;


    private int id;
    private String name;
    private int age;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

 

相关标签: 源码解析