加入收藏 | 设为首页 | 会员中心 | 我要投稿 安卓应用网 (https://www.0791zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Google Protobuf ByteString vs. Byte []

发布时间:2020-05-28 07:36:28 所属栏目:Java 来源:互联网
导读:我正在使用谷歌的protobuf在 Java. 我看到可以将protobuf消息序列化为String,byte [],ByteString等: (来源: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/MessageLite) 我不知道什么是ByteString.我从pro

我正在使用谷歌的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);
  }
}

(编辑:安卓应用网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读