jprotobuf工作原理如下:
- 扫描类上的注解的信息,进行分析(与protobuf读取proto文件进行分析过程相似)
- 根据注解分析的结果,动态生成java代码进行protobuf序列化与反序列化的功能实现
- 使用JDK6及以上的 code compile API进行编译后加载到classloader
github地址:https://github.com/jhunters/jprotobuf
jprotobuf 序列化字节数小,适合网络传输
序列化字段设置:
public class Student{ private static final long serialVersionUID = -2140242550063332020L; @Protobuf(fieldType = FieldType.INT32, order = 1, required = true) private int age; @Protobuf(fieldType = FieldType.STRING, order = 2, required = false) private String name; public static int gender = 1; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student{" + "age=" + age + ", name='" + name + '\'' + '}'; } }
实现序列化:
public class JprotobufDemo { public static void main(String[] args) { Codec<Student> simpleTypeCodec = ProtobufProxy .create(Student.class); Student stu = new Student(); stu.setAge(18); stu.setName("mic"); try { // 序列化 byte[] bb = simpleTypeCodec.encode(stu); // 反序列化 Student newStt = simpleTypeCodec.decode(bb); System.out.println("反序列化结果:"+newStt); } catch (IOException e) { e.printStackTrace(); } } }