1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374 |
- 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;
- /**
- * <pre>
- *
- * Created by IntelliJ IDEA.
- * User: zhenqin
- * Date: 14/12/10
- * Time: 09:55
- * To change this template use File | Settings | File Templates.
- *
- * </pre>
- *
- * @author zhenqin
- */
- public class CompressProtobufKryoSerializer extends com.esotericsoftware.kryo.Serializer<GeneratedMessage> {
- /**
- * 内部缓存
- */
- protected final static Map<Class<?>, Method> CLASS_METHOD_MAP = new HashMap<Class<?>, 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);
- }
- }
|