gpt4 book ai didi

java - 如何从protoc.exe获取类文件

转载 作者:行者123 更新时间:2023-12-01 05:47:18 25 4
gpt4 key购买 nike

我第一次尝试使用 Protocol Buffer 。我正在遵循谷歌提供的教程。我制作的*.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 个错误”。我知道我可能完全迷失了,甚至还没有接近正确的想法......但任何帮助都会很棒!谢谢!

哦,这是调用这个原型(prototype)的代码...

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);
}
}

谢谢!

Link to protobuf tutorial I am using!

最佳答案

只需将 .java 文件包含在 Eclipse 的 src 目录中即可。 Eclipse 会将其编译成 .class 文件。

关于java - 如何从protoc.exe获取类文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5597140/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com