Protobuf - 嵌套类
在这里,我们将了解如何创建嵌套类。Protobuf 将其转换为嵌套 Java 类。
继续使用 theater 示例,以下是我们需要用来指示 Protobuf 我们将创建嵌套类的语法 −
syntax = "proto3";
package theater;
option java_package = "com.tutorialspoint.theater";
message Theater {
TheaterOwner owner = 10;
}
message TheaterOwner{
string name = 1;
string address = 2;
}
现在我们的 class/message 包含一个嵌套类,即有关剧院所有者的信息。
要使用 Protobuf,我们现在必须使用 protoc 二进制文件从此 .proto" 文件创建所需的类。让我们看看如何做到这一点 −
protoc --java_out=java/src/main/java proto_files heater.proto
上述命令应该创建所需的文件,现在我们可以在 Java 代码中使用它。首先,让我们创建一个 writer 来写入 theater 信息 −
package com.tutorialspoint.theater;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tutorialspoint.theater.TheaterOuterClass.Theater;
import com.tutorialspoint.theater.TheaterOuterClass.TheaterOwner;
public class TheaterWriter{
public static void main(String[] args) throws IOException {
TheaterOwner owner = TheaterOwner.newBuilder()
.setName("Anthony Gonsalves")
.setAddress("513, St Paul Street, West Coast, California")
.build();
Theater theater = Theater.newBuilder()
.setOwner(owner)
.build();
String filename = "theater_protobuf_output";
System.out.println("Saving theater information to file: " + filename);
try(FileOutputStream output = new FileOutputStream(filename)){
theater.writeTo(output);
}
System.out.println("Saved theater information with following data to disk:
" + theater);
}
}
接下来,我们有一个reader来读取theater 信息 −
package com.tutorialspoint.theater;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.tutorialspoint.greeting.Greeting.Greet;
import com.tutorialspoint.theater.TheaterOuterClass.Theater;
import com.tutorialspoint.theater.TheaterOuterClass.Theater.Builder;
public class TheaterReader{
public static void main(String[] args) throws IOException {
Builder theaterBuilder = Theater.newBuilder();
String filename = "theater_protobuf_output";
System.out.println("Reading from file " + filename);
try(FileInputStream input = new FileInputStream(filename)) {
Theater theater = theaterBuilder.mergeFrom(input).build();
System.out.println(theater);
}
}
}
现在,编译后,让我们首先执行writer −
> java -cp . arget\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterWriter
Saving theater information to file: theater_protobuf_output
Saved theater information with following data to disk:
owner {
name: "Anthony Gonsalves"
address: "513, St Paul Street, West Coast, California"
}
现在,让我们执行读取器来读取同一个文件 −
java -cp . arget\protobuf-tutorial-1.0.jar com.tutorialspoint.theater.TheaterReader
Reading from file theater_protobuf_output
owner {
name: "Anthony Gonsalves"
address: "513, St Paul Street, West Coast, California"
}
因此,正如我们所见,我们可以通过将二进制数据反序列化为 Theater 对象来读取序列化的嵌套类数据。

