views:

173

answers:

3

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?

+5  A: 

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 youre done:

sudocode:

class Thirdparty{

    int field1;
    int field;
}

class Transfer implements Serializable{

    int field1;
    int field2;

    Constructor(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 for custom serialization
   void writeObject(Stream out);
   void readObject(Stream in);
}

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

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

check here for some serialization infos:

Serialization Secrets

smeg4brains
Thanks, this seems good, what do I do about the private member variables? Is there an easy way for that or do I need reflection?
Kyle
yep reflection is the only way i know of to access non visible fields. :/
smeg4brains
+1  A: 

You need to wrap it into something that does the serialization.

Ideally, the third-party class supports some other form of serialization, for example XML serialization (which is based on bean properties). If not, you have to roll your own. Whether that involves reflection or just getters, setters and constructors depends on the class.

In any case, the wrapper would convert the object into a byte[] or a String or something else and write that into the serialization output. On deserialization it reconstructs the object from that data.

The two methods your wrapper has to implement are

private void writeObject(java.io.ObjectOutputStream out)
 throws IOException
private void readObject(java.io.ObjectInputStream in)
 throws IOException, ClassNotFoundException;
Thilo
A: 

A lot depends on the nature of the third party class. Is it final, does it have a no argument constructor, can you construct it given known values or is it constructed by another class, does it itself contain non-Serializable members?

Easiest way is to decompile the class, add an implements Serializable, and recompile it, but if it contains non-Serializable members, things get more complicated.

Yishai