Getting Started with Protocol Buffers: Serialize and Deserialize Objects in Java
This article introduces Protocol Buffers, explains its advantages over XML, and provides a step‑by‑step guide for defining .proto files, compiling them with protoc, configuring a Java Gradle project, and writing code to serialize and deserialize objects using the generated classes.
Protocol Buffers (ProtoBuf) is a language‑independent, platform‑independent, extensible method for serializing structured data, offering smaller size (3‑10×) and faster speed (20‑100×) compared with XML.
Defining a .proto file
A .proto file describes the data structures. An example defining a Person message with fields and an enum is shown:
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}In protobuf‑3 the required and optional keywords are removed; fields are defined with a type, name, and numeric tag.
Compiling the .proto file
Download the appropriate protoc compiler from the official GitHub releases page, extract it, and add protoc.exe to the system PATH. Running protoc --java_out=src/main/java src/protobuf/Student.proto generates Java classes in the specified output directory.
Setting up a Java project
Create a Gradle (or Maven) project in IntelliJ IDEA and add the protobuf dependencies:
dependencies {
compile ([group:'com.google.protobuf', name:'protobuf-java', version:'3.13.0'],
[group:'com.google.protobuf', name:'protobuf-java-util', version:'3.13.0'])
}The IDE will download the corresponding JAR files from Maven Central.
Writing the .proto for the example
Create Student.proto under src/main/protobuf with the following content:
syntax = "proto3";
package com.badao.protobuf;
option optimize_for = SPEED;
option java_package = "com.badao.protobuf";
option java_outer_classname = "DataInfo";
message Student {
string name = 1;
int32 age = 2;
string address = 3;
}The options set the optimization level, the generated Java package, and the outer class name.
Compiling the .proto to Java classes
Run the protoc command in the terminal (the executable is already in PATH):
protoc --java_out=src/main/java src/protobuf/Student.protoSuccessful execution creates DataInfo.java containing the Student class.
Serializing and deserializing objects
Write a test class that builds a Student instance, converts it to a byte array, and parses it back:
package com.badao.protobuf;
import com.google.protobuf.InvalidProtocolBufferException;
public class ProtobufTest {
public static void main(String[] args) throws InvalidProtocolBufferException {
DataInfo.Student student = DataInfo.Student.newBuilder()
.setName("公众号:霸道的程序猿")
.setAge(100)
.setAddress("中国")
.build();
byte[] bytes = student.toByteArray();
DataInfo.Student student1 = DataInfo.Student.parseFrom(bytes);
System.out.println(student1.getName());
System.out.println(student1.getAge());
System.out.println(student1.getAddress());
}
}The code demonstrates that the generated Student class provides toByteArray() for serialization and parseFrom() for deserialization.
Running the main method prints the original field values, confirming successful round‑trip serialization.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
The Dominant Programmer
Resources and tutorials for programmers' advanced learning journey. Advanced tracks in Java, Python, and C#. Blog: https://blog.csdn.net/badao_liumang_qizhi
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
