Serialize a UUID with XMLEncoder

892 Views Asked by At

I'm using XMLEncoder to write an object graph to a XML file. That works fine, except for the UUID property (which has the name id in my JavaBean) I know that I need a PersistenceDelegate to get it done. I wrote the following one:

class UuidPersistenceDelegate extends PersistenceDelegate {
    protected Expression instantiate(Object oldInstance, Encoder out) {
        UUID id = (UUID) oldInstance;
        return new Expression(oldInstance, id.getClass(), "fromString", new Object[]{ "id" } );
    }
}

And set it to the Encoder:

encoder.setPersistenceDelegate(UUID.class, new UuidPersistenceDelegate());

During runtime I get the following exception when calling encoder.writeObject(...):

java.lang.IllegalArgumentException: Invalid UUID string: id

Does anyone know how to get this to work?

2

There are 2 best solutions below

0
On

Welcome to SO. You are very close to your solution, one minor problem with your code. You are passing in the String "id" into your arguments parameter, which I'm pretty sure you do not want to do. Try this instead:

protected Expression instantiate(Object oldInstance, Encoder out) {
    UUID id = (UUID) oldInstance;
    return new Expression(oldInstance, UUID.class, "fromString", new Object[]{ id.toString() } );
}

The outputted XML is not pretty, but at least you will get rid of your error.

0
On

I haven't seen anyone actually answer this properly and that actually works:

public class UUIDPersistenceDelegate extends PersistenceDelegate {
private HashSet<UUID> hashesWritten = new HashSet<UUID>();

public Expression instantiate(Object oldInstance, Encoder out) {
    UUID id = (UUID) oldInstance;
    hashesWritten.add(id);
    return new Expression(oldInstance, UUID.class, "fromString", new Object[]{ id.toString() } );
}

protected boolean mutatesTo(Object oldInstance, Object newInstance) {
    return hashesWritten.contains(oldInstance);
}

}