Protocol Buffers - message



Overview

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

Example Code

Following is the syntax that we need to have to instruct Protocol Buffers 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.

Explanation

The "syntax" here represents what version of Protocol Buffers 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.

Using multiple message attributes

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. Protocol Buffers 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 {
}

Creating Java Classes from proto file

To use Protocol Buffers, 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=. proto_files\theater.proto

Using Java Classes created from a proto file

Well, that is it! The above command should create the required files in the current directory and now we can use them 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/classe. Let us do that when we look at strings in Protocol Buffers - string chapter.

Advertisements