在java中,如何序列化未标记为Serializable的类? [英] In java how do I serialize a class that is not marked Serializable?

查看:675
本文介绍了在java中,如何序列化未标记为Serializable的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要序列化第三方库中的特定类。我该怎么做呢?

There is a specific class in a third party library that I want to serialize. How would I go about doing this?

我假设我必须编写一个方法来接受类的对象并使用反射来获取私有成员值。然后,为了反序列化,我会使用反射来放回值。

I'm assuming I will have to write a method that takes in an object of the class and uses reflection to get the private member values. Then for deserialization I would use reflection to put the values back.

这会有用吗?有没有更简单的方法?

Would this work? Is there an easier way?

推荐答案

您可以使用实现Serializable的传输对象,并且具有与第三方对象相同的字段。让传输对象实现一个方法,该方法返回原始第三方类的对象并且您已完成:

You could just use a transfer object that implements Serializable, and has the same fields as the third party object. Let the transfer object implement a method that returns an object of the original third party class and you're done:

伪代码:

class Thirdparty{

    int field1;
    int field;
}

class Transfer implements Serializable{

    int field1;
    int field2;

    /* Constructor takes the third party object as 
       an argument for copying the field values.
       For private fields without getters 
       use reflection to get the values */
    Transfer (Thirdparty orig){
       this.field1=orig.field1;
       this.field2=orig.field2;
    }

    ThirdParty getAsThirdParty(){
        Thirdparty copy=new ThirdParty();
        copy.field1=this.field1;
        copy.field2=this.field2;
        return copy;
    }

    /* override these methods for custom serialization */
    void writeObject(OutputStream sink);
    void readObject(InputStream src);
}

如果你有任何成员,你必须确保成员序列化正确特殊成员对象。

You just have to make sure that the members are serialized correctly if you got any special member objects.

或者如果第三方类不是final,你可以只扩展它,让它实现Serializable并编写自己的writeObject和readObject方法。

Alternatively if the third party class isn't final you could just extend it, have that implement Serializable and write your own writeObject and readObject methods.

点击此处查看一些序列化信息:

Check here for some serialization infos:

序列化秘密

这篇关于在java中,如何序列化未标记为Serializable的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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