import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
/**
* 序列化框架Protostuff
*/
public class ProtostuffUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<>();
@SuppressWarnings("unchecked")
private static <T> Schema<T> getSchema(Class<T> cls) {
Schema<T> schema = (Schema<T>) cachedSchema.get(cls);
if (schema == null) {
schema = RuntimeSchema.createFrom(cls);
cachedSchema.put(cls, schema);
}
return schema;
}
@SuppressWarnings("unchecked")
public static <T> byte[] serialize(T obj) {
Class<T> cls = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(cls);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
public static <T> T deserialize(byte[] data, Class<T> cls) {
try {
// 由于这里使用了反射来实例化对象,这要求对象一定要有无参构造器。
// 也就是Message必须要有无参构造器.
// 不想受此限制的话可以使用Objenesis来完成对象的实例化
T message = cls.newInstance();
Schema<T> schema = getSchema(cls);
ProtostuffIOUtil.mergeFrom(data, message, schema);
return message;
} catch (IllegalAccessException | InstantiationException e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
Maven依赖配置如下:
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>${protostuff.version}</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>${protostuff.version}</version>
</dependency>
关于Objenesis
利用Java反射实例化对象必须要有无参构造器,且调用函数不会造成额外的副作用,如你在其中实现特殊的业务逻辑,抛出异常等,因此代码的通用性与健壮性受到影响。
使用Objenesis可以绕过构造器来创建实例。Objenesis实例话对象有许多不同的策略:1,Stardard:没有构造器会被调用。2,Serilizable compliant:与Java标准序列化方式实例话一个对象的行为一致。
最简单的使用Objenesis的方法是使用ObjenesisStd(Standard) 和ObjenesisSerializer(Serializable compliant)。这两种方式会自动选择最好的策略。
来看看如何使用:
Objenesis objenesis = new ObjenesisStd();
XXX xxx = (XXX) objenesis.newInstance(XXX.class);
实例化对象第二种方式。为了提高性能,最好尽可能多的使用ObjectInstantiator 对象。 例如,如果要实例化一个类的多个对象,请使用相同的ObjectInstantiator。
InstantiatorStrategy和ObjectInstantiator都可以在多线程中共享并发使用,它们是线程安全的。
ObjectInstantiator 线程安全,可复用,可提高性能。
Objenesis objenesis = new ObjenesisStd();
ObjectInstantiator instantiator = objenesis .getInstantiatorOf(XXX.class);
XXX xxx = (XXX) instantiator.newInstance();
XXX xxx2 = (XXX) instantiator.newInstance();
XXX xxx3 = (XXX) instantiator.newInstance();
Maven添加如下依赖
<dependency>
<groupId>org.objenesis</groupId>
<artifactId>objenesis</artifactId>
<version></version>
</dependency>