Protobuf - Class/Member



The very basic building block of Protobuf is the member attribute. This translates to a class in the languages that we use, for example, Java, Python, etc.

Following is the syntax that we need to have to instruct Protobuf that we will be creating instances of a given class −

syntax = "proto3";
package theater;
option java_package = "com.tutorialspoint.theater";

message Theater {
}

We will save the above in "theater.proto" and we will use this when we explore other data structures.

The "syntax" here represents what version of Protobuf are we using. So, we are using the latest version 3 and the schema thus can use all the syntax which is valid for version 3.

syntax = "proto3";

The package here is used for conflict resolution, if, say, we have multiple class/message with the same name.

package tutorial;

This argument is specific to Java, i.e., the package where the code from the ".proto" file will be auto-generated.

option java_package = "com.tutorialspoint.greeting";

Now that we are done with the prerequisites, the last item here is −

message Theater

This is nothing but the class name of the base class for the object which would be created/recreated. Note that it is useless in its current shape, as it does not have any other attributes. But we will be more adding attributes as we move along.

A single proto file can also have multiple classes/messages. For example, if we want, we can add a Visitors message/class as well in the same file. Protobuf would ensure to create two separate and independent classes for the same. For example −

syntax = "proto3";

package theater;

option java_package = "com.tutorialspoint.theater";

message Theater {
}
message Visitor {
}

To use Protobuf, we will now have to use protoc binary to create the required classes from this ".proto" file. Let us see how to do that −

protoc  --java_out=java/src/main/java proto_files\theater.proto

Well, that is it! The above command should create the required files and now we can use it in our Java code −

Theater theater = Theater.newBuilder().build()
Visitor visitor = Visitor.newBuilder().build()

At this stage, it is not very useful, as we have not added any attributes to the members/classed. Let us do that when we look at strings.

Advertisements