使用googelprotobuf2.3.0我的protobuf文件中有2个扩展,我在java代码中怎样获取到这2个扩展的值我的值都已经赋好,但是在取值的时候,怎么也取不出扩展中的值,请各位大神帮忙,一下提...
使用googel protobuf 2.3.0 我的protobuf文件中有2个扩展,我在java代码中怎样获取到这2个扩展的值
我的值都已经赋好,但是在取值的时候,怎么也取不出扩展中的值,请各位大神帮忙,一下提供代码和读取后打印的结果
详情请看代码
protobuf文件:
message Foo {
required string t1 = 1;
extensions 100 to 199;
}
message MyTest{
required int32 a = 1;
optional Foo foo = 2;
}
extend Foo{
optional int32 type = 101;
}
extend Foo{
optional string data = 102;
}
java运行类:
//赋值方法
public static void infoProtobuf() {
Test1.MyTest.Builder builder = Test1.MyTest.newBuilder();
Foo.Builder fooBuilder = Foo.newBuilder();
fooBuilder.setT1("t1");
fooBuilder.setExtension(Test1.type, 1);
fooBuilder.setExtension(Test1.data, "DATA");
builder.setA(123);
builder.setFoo(fooBuilder);
Test1.MyTest myTest = builder.build();
System.out.println("赋值结果 : " + myTest);
try {
FileOutputStream output = new FileOutputStream(new File("D:\\test1"));
myTest.writeTo(output);
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
//取值方法
public static void readProtobuf(Test1.MyTest myTest){
System.out.println("取值结果 : ");
System.out.println("a : " + myTest.getA());
System.out.println("t1: "+ myTest.getFoo().getT1());
System.out.println("foo: "+myTest.getFoo().toString().trim());
System.out.println("type: "+myTest.getFoo().getExtension(Test1.type));
System.out.println("data: "+myTest.getFoo().getExtension(Test1.data));
}
//运行方法
public static void main(String[] args) {
RunClass.infoProtobuf();
try {
Test1.MyTest test1 = Test1.MyTest.parseFrom(new FileInputStream(new File("D:\\test1")));
RunClass.readProtobuf(test1);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
这是运行结果
展开