Skip to content

Instantly share code, notes, and snippets.

@shrijeet
Created April 27, 2012 23:30
Show Gist options
  • Save shrijeet/2514272 to your computer and use it in GitHub Desktop.
Save shrijeet/2514272 to your computer and use it in GitHub Desktop.
Thrift + Kyro (courtesy nathan marz)
public class ThriftSerialization extends com.esotericsoftware.kryo.Serializer {
Map<Class, TBase> prototypes;
TSerializer ser;
TDeserializer des;
public ThriftSerialization() {
prototypes = new HashMap<Class, TBase>();
ser = new TSerializer(new TCompactProtocol.Factory());
des = new TDeserializer(new TCompactProtocol.Factory());
}
@Override
public void writeObjectData(ByteBuffer bb, Object o) {
try {
bb.put(ser.serialize((TBase) o));
} catch (TException e) {
throw new RuntimeException(e);
}
}
@Override
public <T> T readObjectData(ByteBuffer bb, Class<T> type) {
if(!prototypes.containsKey(type)) {
try {
prototypes.put(type, (TBase) type.newInstance());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
TBase prototype = prototypes.get(type);
TBase ret = prototype.deepCopy();
try {
ret.read(new TCompactProtocol(new TIOStreamTransport(new ByteBufferInputStream(bb))));
} catch (TException ex) {
throw new RuntimeException(ex);
}
return (T) ret;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment