Java:重构后加载保存在硬盘上的对象=> “未找到类”;例外:/ [英] Java: load an object saved on hard disk after refactoring => "class not found" exception :/

查看:109
本文介绍了Java:重构后加载保存在硬盘上的对象=> “未找到类”;例外:/的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Java开发一个应用程序,该应用程序使用以下简单方法将对象定期保存到硬盘上:

I'm developping an application in java that regulary saves objects onto the hard disk using this simple method:

public void save(String filename)
{
    try
    {
        FileOutputStream fos = new FileOutputStream(filename);
        GZIPOutputStream gzos = new GZIPOutputStream(fos);
        ObjectOutputStream out = new ObjectOutputStream(gzos);
        out.writeObject(this);
        out.flush();
        out.close();
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

}

对象是sebbot的实例.learning.DirectPolicySearch类。

The object is an instance of sebbot.learning.DirectPolicySearch class.

问题在于,经过一些重构,学习包被重命名为'ballcapture'。现在,当我尝试加载保存的文件时,出现以下异常:

The problem is, after some refactoring, the learning package was renamed to 'ballcapture'. Now, when I try to load a saved file, I get the following exception:

java.lang.ClassNotFoundException:sebbot.learning.DirectPolicySearch

java.lang.ClassNotFoundException: sebbot.learning.DirectPolicySearch

我用来加载文件的方法是:

The method I use to load the file is:

public static synchronized DirectPolicySearch load(String filename)
{
    DirectPolicySearch dps = null;
    try
    {
        FileInputStream fis = new FileInputStream(filename);
        GZIPInputStream gzis = new GZIPInputStream(fis);
        ObjectInputStream in = new ObjectInputStream(gzis);
        dps = (DirectPolicySearch) in.readObject();
        in.close();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    System.out.println(dps);

    return dps;
}

有人可以帮助我吗?
非常感谢。

Can anyone help me with this ? Thanks a lot.

推荐答案

类名更改(包括程序包名称更改)是打破规则的保证方法。序列化机制;

Class name changes (which includes package name changes) are the guaranteed way to break the serialization mechanism; it's simply not designed to work with classes that change names.

几乎唯一可以做的就是撤消重构以获取原始命名的类,然后获取当前版本放入同一工作区,请使用原始类进行反序列化,以编程方式将其内容复制到重构类的实例中,然后对其进行序列化。

Pretty much the only thing you can do is to undo the refactoring to get the originally named class, then get the current version into the same workspace, use the original class to deserialize, programmatically copy its contents into an instance of the refactored class and then serialize that.

为了避免这种麻烦,请考虑使用更健壮和灵活的序列化方法,例如 XStream

If you want to be safe from that kind of hassle, consider using a more robust and flexible serialization method like XStream.

这篇关于Java:重构后加载保存在硬盘上的对象=> “未找到类”;例外:/的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆