Is there a way to make readExternal() use another constructor?

49 Views Asked by At

I was trying to implement readExternal from the Externalizable interface in order to serialize my big object more efficiently when I realised there is no way I can make a new object (and use it) within that method. The point is that my efficient representation needs to be deciphered and therefore I can't assign my fields directly. The code looks as follows:

public class BigObject implements Externalizable {

    //lots of fields and methods...

    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(this.encode()); //encodes to a BigInteger
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        BigInteger code = (BigInteger) in.readObject();
        BigObject bo = BigObject.decode(code);
        // now I would like this to be "bo"
    }
}

For now I copy all fields from the object I get, but it looks ugly and I wanted to know whether there would be a nicer way to something like this?

1

There are 1 best solutions below

2
On

The problem is that your encode and decode methods are not consistent. The decode is a static method and encode is not. My suggestion will be to make decode non static.