我第一次尝试使用协议缓冲区。我正在按照谷歌提供的教程。我做的* .proto如下:
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;
}
然后我使用以下命令编译它:
protoc -I=../examples --java_out=src/main/java ../examples/addressbook.proto
它运行时没有错误并生成addressbook.java。但是从我所知道的,我需要一个* .class,以便我可以在eclipse环境中使用它。我尝试使用以下命令将其输出到* .jar文件:
protoc -I=../examples --java_out=src/main/java/addressbook.jar ../examples/addressbook.proto
但是在将该jar导入项目之后,eclipse说我需要课程。我在示例目录中尝试使用该命令将其编译为类。
javac *java
它看到了文件,但返回了大量的行,后跟“100个错误”。我明白我可能完全迷失了,甚至没有接近正确的想法......但任何帮助都会很棒!谢谢!
哦,这是调用此原型的代码......
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);
}
}
谢谢!
答案 0 :(得分:0)
只需在eclipse的src目录中包含.java文件即可。 Eclipse会将其编译为.class文件。