我在访问扩展 Protocol Buffer 成员时遇到问题。这是场景:
Message Foo { optional int i = 1; }
message Bar { extend Foo {
optional int j = 10001; } }
我的任何其他原型(prototype)中都没有 Bar 消息。如何在 Java 中获取 Bar.j?我发现的所有示例都需要在消息中使用 Bar。
谢谢!
最佳答案
Protocol Buffer 中的扩展并不一定像您期望的那样工作,即它们不匹配 Java 继承机制。
针对您的问题,我创建了以下 foobar.proto
文件:
package test;
message Foo {
optional int32 i = 1;
extensions 10 to 99999;
}
message Bar {
extend Foo {
optional int32 j = 10001;
}
}
它创建 Foobar.java
,包含类 Foobar.Bar
和 Foobar.Foo
。
这是一个访问 Bar.j 的简单 JUnit 测试用例:
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import test.Foobar.Bar;
import test.Foobar.Foo;
public class TestFooBar {
@Test
public void testFooBar() {
Foo foo = Foo.newBuilder().setI(123).setExtension(Bar.j, 456).build();
assertEquals(Integer.valueOf(456), foo.getExtension(Bar.j));
}
}
希望这有助于澄清您的问题!
关于java - 在 Java 中扩展 Protocol Buffers,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9441016/