Using Protobuf in Java

The main steps to using protobuf in Java are as follows:

  1. To define message types: first, a .proto file needs to be created in order to define message types and fields. For example, a message type named Person can be defined, which includes fields for name and age.
syntax = "proto3";

message Person {
  string name = 1;
  int32 age = 2;
}
  1. Create Java classes: Compile the .proto file into Java classes using the protobuf compiler. Generate Java classes by running the following command in the terminal.
protoc --java_out=[输出目录] [proto文件]

This will create a Java class named Person.java, which contains methods for serializing and deserializing messages.

  1. convert to byte array
  2. convert into a readable format

Here is a simple example code:

import com.example.Person;

public class ProtobufExample {
  public static void main(String[] args) throws Exception {
    // 创建一个Person消息对象并设置字段值
    Person person = Person.newBuilder()
        .setName("Alice")
        .setAge(25)
        .build();

    // 将消息序列化为字节数组
    byte[] serializedPerson = person.toByteArray();

    // 将字节数组反序列化为Person消息对象
    Person deserializedPerson = Person.parseFrom(serializedPerson);

    // 使用反序列化后的消息对象
    System.out.println("Name: " + deserializedPerson.getName());
    System.out.println("Age: " + deserializedPerson.getAge());
  }
}

This is a simple example of using protobuf, demonstrating how to create, serialize, and deserialize a Person message object. In fact, protobuf also offers many other features such as support for nested messages, enum types, default values, and more. You can learn more about protobuf in the official documentation.

bannerAds