Java: Protocol Buffer 不生成解析函数

Java: Protocol Buffer does not generate parsing functions

我有以下 .proto 文件:

message MediatorMessageMsg{
    required double speed = 1;
    required double heading = 2;

    required string sender = 3;
}

并且我使用带有 Protocol Buffer 2.5.0 版本的 Eclipse Mars。它生成必要的文件(我们不应该编辑)但是我不能使用

的重要功能

没有这些,使用整个东西就毫无意义。我检查了文件,我可以在那里看到 parseDelimitedFrom() ,但是我不能在我自己的项目中调用它(是的,已经导入)。当我将鼠标悬停在错误上时,它会显示以下内容:

The method parseDelimitedFrom(ByteArrayInputStream) is undefined for the type MediatorMessage

有人知道为什么会这样吗?

编辑:关于这个问题的更多细节。

例如,我无法使用下面的功能来构建我的消息。它会引发错误。

MediatorMessage mediatorMessage = MediatorMessage.newBuilder().

或者我不能这样做

ByteArrayOutputStream output = new ByteArrayOutputStream(bufferSize);
mediatorMessage.writeDelimitedTo(output);

或这个

ByteArrayInputStream firstInput = new ByteArrayInputStream(buf);
mediatorMessageOne = MediatorMessage.parseDelimitedFrom(firstInput);

所以这些函数由于某些原因无法识别。

因为您还没有回答 *.proto 文件中的 MediatorMessageMsg 是如何变成 MediatorMessage.java 的,请在下面找到一个精简的示例。这应该会为您指明正确的方向。

假设以下目录和文件结构,假设安装了 protoc 并且在您的 PATH.

bin/
lib/protobuf-java-2.5.0.jar
src/Check.java
MediatorMessage.proto

src/Check.java

import com.google.protobuf.TextFormat;
import sub.optimal.MediatorMessage.MediatorMessageMsg;

class Check {
    public static void main(String...args) {
        MediatorMessageMsg.Builder builder = MediatorMessageMsg.newBuilder();
        MediatorMessageMsg msg = builder.setSpeed(42.0)
                .setHeading(0.0)
                .setSender("foobar")
                .build();

        System.out.println(TextFormat.shortDebugString(msg));
    }
}

MediatorMessage.proto

option java_package = "sub.optimal";
option java_outer_classname = "MediatorMessage";

message MediatorMessageMsg{
    required double speed = 1;
    required double heading = 2;

    required string sender = 3;
}
  • 从 proto 文件生成 Java 源代码

    protoc --java_out=src/ MediatorMessage.proto
    

    这会生成 Java 源文件 src/sub/optimal/MediatorMessage.java

  • 编译 Java 来源

    javac -cp lib/protobuf-java-2.5.0.jar:src/. -d bin/ src/Check.java
    

    这会生成文件

    bin/Check.class
    bin/sub/optimal/MediatorMessage.class
    bin/sub/optimal/MediatorMessage$MediatorMessageMsg.class
    bin/sub/optimal/MediatorMessage$MediatorMessageMsg$Builder.class
    bin/sub/optimal/MediatorMessage$MediatorMessageMsg.class
    bin/sub/optimal/MediatorMessage$MediatorMessageMsgOrBuilder.class
    bin/sub/optimal/MediatorMessage.class
    
  • 运行 简单检查

    java -cp lib/protobuf-java-2.5.0.jar:bin/ Check
    

输出

speed: 42.0 heading: 0.0 sender: "foobar"