Protostuff序列化框架的使用及Objenesis的使用

本文介绍了Objenesis框架的使用,它允许不通过构造器创建对象,提高了代码的通用性和健壮性。Maven依赖配置、Objenesis的两种策略——Standard和Serializable compliant,以及如何在多线程环境中使用ObjectInstantiator以提升性能,都进行了详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值