I am trying to use protocol buffers for my first time. I am following the tutorial provided by google. The *.proto I make is as follows:
package tutorial;
option java_package = "com.example.tutorial";
option java_outer_classname = "AddressBookProtos";
message Person {
required string name = 1;
required int32 id = 2;
optional string email = 3;
enum PhoneType {
MOBILE = 0;
HOME = 1;
WORK = 2;
}
message PhoneNumber {
required string number = 1;
optional PhoneType type = 2 [default = HOME];
}
repeated PhoneNumber phone = 4;
}
message AddressBook {
repeated Person person = 1;
}
I then compile it with the following command:
protoc -I=../examples --java_out=src/main/java ../examples/addressbook.proto
It runs without error and produces addressbook.java. But from what I can tell, I need a *.class so that I can use this in the eclipse environment. I have tried outputting it to a *.jar file with the command:
protoc -I=../examples --java_out=src/main/java/addressbook.jar ../examples/addressbook.proto
But after importing that jar to a project, eclipse says I need classes. I have also tried compiling it to a class with the command while I am in the examples directory.
javac *java
It sees the file but returns a ton of lines followed by "100 errors". I understand that I may be completely lost and not even close to the right idea... but any help would be great! Thanks!
oh and here is the code that calls this proto...
import com.example.tutorial.AddressBookProtos.AddressBook;
import com.example.tutorial.AddressBookProtos.Person;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintStream;
class ListPeople {
// Iterates though all people in the AddressBook and prints info about them.
static void Print(AddressBook addressBook) {
for (Person person: addressBook.getPersonList()) {
System.out.println("Person ID: " + person.getId());
System.out.println(" Name: " + person.getName());
if (person.hasEmail()) {
System.out.println(" E-mail address: " + person.getEmail());
}
for (Person.PhoneNumber phoneNumber : person.getPhoneList()) {
switch (phoneNumber.getType()) {
case MOBILE:
System.out.print(" Mobile phone #: ");
break;
case HOME:
System.out.print开发者_开发百科(" Home phone #: ");
break;
case WORK:
System.out.print(" Work phone #: ");
break;
}
System.out.println(phoneNumber.getNumber());
}
}
}
// Main function: Reads the entire address book from a file and prints all
// the information inside.
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("Usage: ListPeople ADDRESS_BOOK_FILE");
System.exit(-1);
}
// Read the existing address book.
AddressBook addressBook =
AddressBook.parseFrom(new FileInputStream(args[0]));
Print(addressBook);
}
}
THANKS!
Link to protobuf tutorial I am using!
Just include the .java file in your src directory in eclipse. Eclipse will compile it into a .class file.
精彩评论