下载编译器
https://github.com/protocolbuffers/protobuf/releases
配置环境变量
在命令行工具进行验证
创建.proto文件定义类结构
在命令行使用protoc命令进行编译
protoc --java_out=src/main/java src/protobuf/Student.proto
即可在指定的src/main/java目录下生成编译后的文件
对类实例进行序列化和反序列化验证
public class ProtoBufTest {
public static void main(String
[] args
) throws InvalidProtocolBufferException
{
DataInfo
.Student student
= DataInfo
.Student
.newBuilder()
.setName("张三")
.setAge(20)
.setAddress("青岛")
.build();
byte[] bytes
=student
.toByteArray();
DataInfo
.Student student1
=DataInfo
.Student
.parseFrom(bytes
);
System
.out
.println(student1
);
System
.out
.println(student1
.getName());
System
.out
.println(student1
.getAge());
System
.out
.println(student1
.getAddress());
}
}