The PdxSerializer interface allows domain classes to be
serialized and deserialized as PDXs without modification
of the domain class. It only requires that the domain class
have a public zero-arg constructor and that it provides read and write access
to the PDX serialized fields.
GemFire allows a single PdxSerializer to be configured on a cache
using
com.gemstone.gemfire.cache.CacheFactory#setPdxSerializer(PdxSerializer)or
com.gemstone.gemfire.cache.client.ClientCacheFactory#setPdxSerializer(PdxSerializer).
It can also be configured in cache.xml
using the pdx-serializer
element.
The same PdxSerializer should be configured on each member of a distributed
system that can serialize or deserialize PDX data.
The
#toData method is used for serialization;
#fromData is used for deserialization.
The order in which fields are serialized and deserialized in these methods for the same class must match.
For the same class toData and fromData must write the same fields each time they are called.
If you can modify your domain class then use
PdxSerializable instead.
Simple example:
public class User {
final public String name;
final public int userId;
public User(String name, int userId) {
this.name = name;
this.userId = userId;
}
}
public class MyPdxSerializer implements PdxSerializer {
public boolean toData(Object o, PdxWriter out) {
if (o instanceof User) {
User u = (User)o;
out.writeString("name", u.name);
out.writeInt("userId", u.userId);
return true;
} else {
return false;
}
}
public Object fromData(Class clazz, PdxReader in) {
if (User.class.isAssignableFrom(clazz)) {
return new User(in.readString("name"), in.readInt("userId"));
} else {
return null;
}
}
}