
wang.moshu.message.ConvertUtil Maven / Gradle / Ivy
package wang.moshu.message;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
public class ConvertUtil
{
private static Map, Schema>> cachedSchema = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
private static Schema getSchema(Class cls)
{
Schema schema = (Schema) cachedSchema.get(cls);
if (schema == null)
{
schema = RuntimeSchema.createFrom(cls);
if (schema != null)
{
cachedSchema.put(cls, schema);
}
}
return schema;
}
@SuppressWarnings("unchecked")
public static byte[] serialize(T obj)
{
Class cls = (Class) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try
{
Schema schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
}
catch (Exception e)
{
throw new IllegalStateException(e.getMessage(), e);
}
finally
{
buffer.clear();
}
}
public static T unserialize(byte[] data, Class cls)
{
try
{
T message = cls.newInstance();
Schema schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
}
catch (Exception e)
{
throw new IllegalStateException(e.getMessage(), e);
}
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy