簡體   English   中英

如何在 Java 中使用 Any protobuf 類型?

[英]How to use Any protobuf type in Java?

下面的代碼不起作用。 這是使用Any的最佳方式嗎? 我正在嘗試讀取/寫入Any並識別Any存儲的類型。

我的.proto

  syntax = "proto3";
  import "google/protobuf/any.proto";
  message CommandListPrinters {
  }
  message Commands {
    int32 id = 1;
    repeated google.protobuf.Any command = 2;
  }

my.java

  CommandListPrinters commandListPrinters = CommandListPrinters.newBuilder().build();
  Any any = Any.newBuilder()
               .setValue(commandListPrinters.toByteString()).build();
  Commands.Builder commandsBuilder = Commands.newBuilder().setId(0);
  commandsBuilder.addCommand(any);
  Commands commands = commandsBuilder.build();
  //
  byte [] ba = commands.toByteArray();      
  Commands cmds2 = Commands.parseFrom(ba);
  for (Any any2 : cmds2.getCommandList()) {
    Descriptor fe = any2.getDescriptorForType();
    // This IF is FALSE;
    if (fe.equals(CommandListPrinters.getDescriptor()) ) {
      CommandListPrinters cmdLR = CommandListPrinters.parseFrom(any2.getValue());
    }
  }

我是 stackoverflow 的新手,所以無法發表評論,但我想知道:為什么您的 CommandListPrinters 消息沒有字段?

打電話

CommandListPrinters.getDescriptor()

讓我覺得 CommandListPrinters 應該有一個字段描述符。 此外,Any proto 也沒有名為 descriptor_for_type 的字段。 https://github.com/google/protobuf/blob/master/src/google/protobuf/any.proto所以

 Descriptor fe = any2.getDescriptorForType();

也沒有多大意義。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM