您的位置:首页 > 编程语言 > Java开发

Java利用protostuff实现高效序列化

2017-01-16 10:07 369 查看
pom内容:

<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-api</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-collectionschema</artifactId>
<version>1.0.10</version>
</dependency>

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 <T> byte[] toByte(T source, Class<T> targetClass) {
RuntimeSchema<T> 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> T toBean(byte[] source, Class<T> targetClass) throws InstantiationException, IllegalAccessException {
RuntimeSchema<T> schema = RuntimeSchema.createFrom(targetClass);
System.out.println(targetClass);
T newInstance = targetClass.newInstance();
ProtostuffIOUtil.mergeFrom(source, newInstance, schema);

return newInstance;
}

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

public static <T> T readBeanFromFile(File sourceFile, Class<T> targetClass) throws InstantiationException, IllegalAccessException, IOException {
byte[] source = FileUtils.readFileToByteArray(sourceFile);
return toBean(source, targetClass);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JAVA 序列化