性能最好的序列化反序列化,Protobuf的用法(maven项目)

首先要在pom.xml里添加Protobuf的jar包

     
          com.dyuproject.protostuff
          protostuff-core
          1.0.8
      

      
          com.dyuproject.protostuff
          protostuff-runtime
          1.0.8
      

序列化的实体类User.java(不需要实现Serializable接口)

package com.serialize.entity;

public class User {
	private String id;
	private String username;
	private String password;
	
	public User() {
	}
	public User(String id, String username, String password) {
		this.id = id;
		this.username = username;
		this.password = password;
	}
	public String getId() {
		return id;
	}
	public void setId(String id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password="
				+ password + "]";
	}
	

}
序列化的工具类SerializeUtils.java(使用了泛型方法)

package com.serialize.utils;

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

public class SerializeUtils{
	public static  byte[] serialize(T t,Class clazz) {
		return ProtobufIOUtil.toByteArray(t, RuntimeSchema.createFrom(clazz),
				LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
	}
	public static  T deSerialize(byte[] data,Class clazz) {
		RuntimeSchema runtimeSchema = RuntimeSchema.createFrom(clazz);
		T t = runtimeSchema.newMessage();
		ProtobufIOUtil.mergeFrom(data, t, runtimeSchema);
		return t;
	}
}
测试主类App.java

package com.serialize;

import com.serialize.entity.User;
import com.serialize.utils.SerializeUtils;

public class App {
	public static void main(String[] args) {	
		User user=new User("1","xiaobao","123456");
		System.out.println("序列化");
		byte[] data = SerializeUtils.serialize(user,User.class);
		for (byte b : data) {
			System.out.print(b);
		}
		System.out.println();
		System.out.println("反序列化");
		User user2 = SerializeUtils.deSerialize(data,User.class);
		System.out.println(user2);
	}
}

你可能感兴趣的:(性能最好的序列化反序列化,Protobuf的用法(maven项目))