Java利用protostuff实现高效序列化

pom内容:


    commons-io
    commons-io
    2.4



            com.dyuproject.protostuff
            protostuff-core
            1.0.10
        
        
            com.dyuproject.protostuff
            protostuff-api
            1.0.10
        
        
            com.dyuproject.protostuff
            protostuff-runtime
            1.0.10
        
        
            com.dyuproject.protostuff
            protostuff-collectionschema
            1.0.10
        


TIP:使用时需要注意的是,那个bean必须要含有无参构造,并且不能是接口或者抽象类(如使用toBean方法时,不能传Runnable这个接口的class的进来,而是应该传自己实际实现了Runnable接口的类的class,并且还必须有无参的构造函数)
示例:Runnable job = SerializingUtil.readBeanFromFile(jobFile, CloseCompetitionJob.class);


import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.runtime.RuntimeSchema;

public class SerializingUtil {

    public static  byte[] toByte(T source, Class targetClass) {
        RuntimeSchema schema = RuntimeSchema.createFrom(targetClass);
        LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
        byte[] protostuff = null;
        try {
            protostuff = ProtostuffIOUtil.toByteArray(source, schema, buffer);

            return protostuff;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            buffer.clear();
        }
        return null;
    }

    public static  T toBean(byte[] source, Class targetClass) throws InstantiationException, IllegalAccessException {
        RuntimeSchema schema = RuntimeSchema.createFrom(targetClass);
        System.out.println(targetClass);
        T newInstance = targetClass.newInstance();
        ProtostuffIOUtil.mergeFrom(source, newInstance, schema);

        return newInstance;
    }

    public static  void writeBeanToFile(T source, Class targetClass, File targetFile) throws IOException {
        byte[] classByte = toByte(source, targetClass);
        FileUtils.writeByteArrayToFile(targetFile, classByte);
    }

    public static  T readBeanFromFile(File sourceFile, Class targetClass) throws InstantiationException, IllegalAccessException, IOException {
        byte[] source = FileUtils.readFileToByteArray(sourceFile);
        return toBean(source, targetClass);
    }
}


你可能感兴趣的:(Java杂七杂八)