Reputation: 2499
I watched a lot of tutorials, but I can not understand how to use protocol buffers
Why "message User "? why not "class User "? and how Eclipse has created such a message? and why name = 2 ? not name = "Max"
ption java_outer_classname="ProtoUser";
message User {
required int32 id = 1; // DB record ID
required string name = 2;
required string firstname = 3;
required string lastname = 4;
required string ssn= 5;
// Embedded Address message spec
message Address {
required int32 id = 1;
required string country = 2 [default = "US"];;
optional string state = 3;
optional string city = 4;
optional string street = 5;
optional string zip = 6;
enum Type {
HOME = 0;
WORK = 1;
}
optional Type addrType = 7 [default = HOME];
}
repeated Address addr = 16;
}
Upvotes: 2
Views: 6428
Reputation: 715
Protobuffer use message(keyword) instead of class Inside the class you define the structure of. schema. For example
message Person{
string name = 1;
repeated string id = 2;
Type phoneType = 3;
}
enum Type{
CellPhone = 0;
HomePhone = 1;
}
In the above example, we are defining the structure of the Person Message. It has name which datatype is a string, id which is an array of the string and type(when you expect only certain values then use an enum. In this case, we assume that phoneNumber can be either CellPhone or HomePhone. If someone is sending any other value then IT will through UNKNOWN proto value exception)
required: means parameter is required
To use proto first create proto classes using mvn clean install Then create protobuilder Protobuilder to set for above proto
Person person = Person.newBuilder().setName("testName")
.setPhoneType(Type.CellPhone)
.addAllId(listIds)
.build;
Once you set the value you can not change it. If you want to change the value then you need to create another proto. Pesron person1 = Person.newBuilder(person).setName("ChangeName").build;
person1 will have the name ChangeName, phoneType CellPhone, and ids arrays of strings.
More information: https://developers.google.com/protocol-buffers
Upvotes: 0
Reputation: 9579
Why "message User "? why not "class User "?
Google Protocol Buffers (GPB) does not have class
in its syntax, it has message
instead.
https://developers.google.com/protocol-buffers/docs/style
This file is just text file, it should have .proto
extension. After all you will run a utility on it which would generate real Java classes which you can import and easily use in your project.
https://developers.google.com/protocol-buffers/docs/javatutorial
Compiling Your Protocol Buffers
protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
required string lastname = 4;
4 stands for the field id, not a value, it is going to be used to generate a bit stream.
Upvotes: 4