大家好,又见面了,我是你们的朋友全栈君。
Protostuff使用示例
- 2018.5.17
- 版权声明:本文为博主chszs的原创文章,未经博主允许不得转载。
1、引入Maven依赖的JAR包
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.5.9</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-api</artifactId>
<version>1.5.9</version>
</dependency>
2、编写需要被序列化的实体类
这里是User.java(成员属性包含了其它类)
package demo.protostuff;
import java.util.List;
public class User {
private String firstName;
private String lastName;
private String email;
private List<User> friends;
private List<Car> cars;
public User() {
}
public User(String email) {
this.email = email;
}
// getters and setters
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public List<User> getFriends() {
return friends;
}
public void setFriends(List<User> friends) {
this.friends = friends;
}
public List<Car> getCars() {
return cars;
}
public void setCars(List<Car> cars) {
this.cars = cars;
}
@Override
public String toString() {
return "User{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email
+ '\'' + ", friends=" + friends + ", cars=" + cars + '}';
}
}
Car.java
package demo.protostuff;
public class Car {
private String color;
private String car_name;
private Integer price;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public String getCar_name() {
return car_name;
}
public void setCar_name(String car_name) {
this.car_name = car_name;
}
public Integer getPrice() {
return price;
}
public void setPrice(Integer price) {
this.price = price;
}
public Car(String car_name) {
super();
this.car_name = car_name;
}
public Car() {
super();
}
@Override
public String toString() {
return "Car [color=" + color + ", car_name=" + car_name + ", price=" + price + "]";
}
}
3、主程序类
这里是App.java
package demo.protostuff;
import java.util.ArrayList;
import java.util.List;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.runtime.RuntimeSchema;
public class App {
private static RuntimeSchema<User> schema = RuntimeSchema.createFrom(User.class);
public static void main(String[] args) {
User user1 = new User();
user1.setEmail("10000@qq.com");
user1.setFirstName("zhang");
user1.setLastName("sanfeng");
List<User> users = new ArrayList<>();
users.add(new User("20000@qq.com"));
user1.setFriends(users);
Car car1 = new Car("宾利");
Car car2 = new Car("法拉利");
List<Car> cars = new ArrayList<>();
cars.add(car1);
cars.add(car2);
user1.setCars(cars);
byte[] bytes = ProtostuffIOUtil.toByteArray(user1, schema,
LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE));
User user2 = schema.newMessage();
ProtostuffIOUtil.mergeFrom(bytes, user2, schema);
System.out.println(user2);
System.out.println();
// 使用自定义的工具类
byte[] bytes1 = ProtostuffUtil.serializer(user1);
User newUser = ProtostuffUtil.deserializer(bytes1, User.class);
System.out.println(newUser);
}
}
程序说明:
- RuntimeSchema类用于在运行时从Java实体对象中生成所需的模式Schema
- ProtostuffIOUtil是一个工具类,用于对消息或对象进行序列化/反序列化
- LinkedBuffer是一个缓冲区类,它封装了字节数组并具有对下一个缓冲区的引用以便能动态增加容量。
执行程序,输出如下:
User{firstName=’zhang’, lastName=’sanfeng’, email=’10000@qq.com’, friends=[User{firstName=’null’, lastName=’null’, email=’20000@qq
.com’, friends=null, cars=null}], cars=[Car [color=null, car_name=宾利, price=null], Car [color=null, car_name=法拉利, price=null]]}
User{firstName=’zhang’, lastName=’sanfeng’, email=’10000@qq.com’, friends=[User{firstName=’null’, lastName=’null’, email=’20000@qq
.com’, friends=null, cars=null}], cars=[Car [color=null, car_name=宾利, price=null], Car [color=null, car_name=法拉利, price=null]]}
4、根据Protostuff库自行封装的工具类
这里是ProtostuffUtil.java
package demo.protostuff;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;
public class ProtostuffUtil {
private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
private static <T> Schema<T> getSchema(Class<T> clazz) {
@SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
if (schema == null) {
schema = RuntimeSchema.getSchema(clazz);
if (schema != null) {
cachedSchema.put(clazz, schema);
}
}
return schema;
}
/**
* 将对象序列化
* @param obj 对象
* @return
*/
public static <T> byte[] serializer(T obj) {
@SuppressWarnings("unchecked")
Class<T> clazz = (Class<T>) obj.getClass();
LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
try {
Schema<T> schema = getSchema(clazz);
return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
} finally {
buffer.clear();
}
}
/**
* 将字节数组数据反序列化
* @param data 字节数组
* @param clazz 对象
* @return
*/
public static <T> T deserializer(byte[] data, Class<T> clazz) {
try {
T obj = clazz.newInstance();
Schema<T> schema = getSchema(clazz);
ProtostuffIOUtil.mergeFrom(data, obj, schema);
return obj;
} catch (Exception e) {
throw new IllegalStateException(e.getMessage(), e);
}
}
}
发布者:全栈程序员-用户IM,转载请注明出处:https://javaforall.cn/133770.html原文链接:https://javaforall.cn
【正版授权,激活自己账号】: Jetbrains全家桶Ide使用,1年售后保障,每天仅需1毛
【官方授权 正版激活】: 官方授权 正版激活 支持Jetbrains家族下所有IDE 使用个人JB账号...