引入jar
com.dyuproject.protostuff
protostuff-api
1.0.10
com.dyuproject.protostuff
protostuff-core
1.0.10
com.dyuproject.protostuff
protostuff-runtime
1.0.10
工具类
import com.dyuproject.protostuff.linkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
public class ProtostuffUtil {
private static Map, Schema>> cachedSchema = new ConcurrentHashMap, Schema>>();
private static Schema getSchema(Class clazz) {
@SuppressWarnings("unchecked")
Schema schema = (Schema) cachedSchema.get(clazz);
if (schema == null) {
schema = RuntimeSchema.getSchema(clazz);
if (schema != null) {
cachedSchema.put(clazz, schema);
}
}
return schema;
}
public static byte[] serialize(T obj) {
@SuppressWarnings("unchecked")
Class clazz = (Class) obj.getClass();
linkedBuffer buffer = linkedBuffer.allocate(linkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema schema = getSchema(clazz);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
public static T deserialize(byte[] data, Class clazz) {
try {
T obj = clazz.newInstance();
Schema schema = getSchema(clazz);
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
public static void main(String[] args) {
byte[] userBytes = ProtostuffUtil.serialize(new TIMReqMsg(1L, "wang", 1));
TIMReqMsg reqProtocol = ProtostuffUtil.deserialize(userBytes, TIMReqMsg.class);
System.out.println(reqProtocol);
}
}



