java – Google Protobuf ByteString vs. Byte []

我正在使用谷歌的protobuf在 Java.
我看到可以将protobuf消息序列化为String,byte [],ByteString等:
(来源: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite)

我不知道什么是ByteString.我从protobuf api文档中得到以下定义(来源:https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/ByteString):
“不可变字节序列.Substring是通过共享对不可变的底层字节的引用来支持的,就像String一样.

我不清楚ByteString如何与String或byte []不同.
有人可以解释一下吗
谢谢.

解决方法

您可以将ByteString视为不可变字节数组.几乎是这样这是一个字节[],您可以在protobuf中使用. Protobuf不允许您使用Java数组,因为它们是可变的.

ByteString存在,因为String不适合表示任意的字节序列.字符串专用于字符数据.

The protobuf MessageLite Interface provides toByteArray() and toByteString() methods. If ByteString is an immutable byte[],would the byte representation of a message represented by both ByteString and byte[] be the same?

有点.如果你调用toByteArray(),你将得到相同的值,就像你调用toByteString().toByteArray()一样.比较两个方法的实现,在AbstractMessageLite中:

public ByteString toByteString() {
  try {
    final ByteString.CodedBuilder out =
      ByteString.newCodedBuilder(getSerializedSize());
    writeto(out.getCodedOutput());
    return out.build();
  } catch (IOException e) {
    throw new RuntimeException(
      "Serializing to a ByteString threw an IOException (should " +
      "never happen).",e);
  }
}

public byte[] toByteArray() {
  try {
    final byte[] result = new byte[getSerializedSize()];
    final CodedOutputStream output = CodedOutputStream.newInstance(result);
    writeto(output);
    output.checkNoSpaceLeft();
    return result;
  } catch (IOException e) {
    throw new RuntimeException(
      "Serializing to a byte array threw an IOException " +
      "(should never happen).",e);
  }
}

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...