Database Reference
In-Depth Information
Tutorial Links
Google provides excellent tutorials for a variety of languages in the
official project docu-
Example Code
tegrated into your development and build process. You begin by defining a model in a
.proto
file. For example:
message Review {
required string reviewer = 1;
required string movieTitle = 2;
required int32 rating = 3;
}
You then run a protobuf compiler for your specific development language (e.g., Java) to gen-
erate code based on your model definition.
The mechanism for working with the objects generated by the protobuf compiler changes
slightly from language to language. In Java, we use a builder to create a new, writeable ob-
ject:
Review
.
Builder
reviewBuilder
=
Review
.
newBuilder
();
reviewBuilder
.
setReviewer
(
"Kevin"
);
reviewBuilder
.
setMovieTitle
(
"Dune"
);
reviewBuilder
.
setRating
(
10
);
Review review
=
reviewBuilder
.
build
();
This review object can then be written to any sort of output stream:
FileOutputStream output
=
new
new
FileOutputStream
(
"review.dat"
);
review
.
writeTo
(
output
);
Repopulating objects from previously serialized data is done in a similar fashion: