package com.sdyc.ndmp.protobuf.serializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import com.google.protobuf.GeneratedMessage;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;
/**
*
*
* Created by IntelliJ IDEA.
* User: zhenqin
* Date: 14/12/10
* Time: 09:55
* To change this template use File | Settings | File Templates.
*
*
*
* @author zhenqin
*/
public class CompressProtobufKryoSerializer extends com.esotericsoftware.kryo.Serializer {
/**
* 内部缓存
*/
protected final static Map, Method> CLASS_METHOD_MAP = new HashMap, Method>(3);
public CompressProtobufKryoSerializer() {
}
@Override
public void write(Kryo kryo, Output output, GeneratedMessage object) {
byte[] bytes = object.toByteArray();
output.writeInt(bytes.length, false);
output.write(bytes);
}
@Override
public GeneratedMessage read(Kryo kryo, Input input, Class type) {
int i = input.readInt(false);
byte[] bytes = new byte[i];
input.read(bytes);
try {
return reflact(type, bytes);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
protected static GeneratedMessage reflact(Class aClass, byte[] args)
throws ClassNotFoundException, NoSuchMethodException,
InvocationTargetException, IllegalAccessException {
Method method = CLASS_METHOD_MAP.get(aClass);
if (method == null) {
method = aClass.getMethod("parseFrom", byte[].class);
CLASS_METHOD_MAP.put(aClass, method);
}
return (GeneratedMessage) method.invoke(null, args);
}
}