java – Google Protobuf ByteString vs. Byte []

I'm using Google's protobuf in Java

I don't know what bytestring is I get the following definitions from the protobuf API document (source: https://developers.google.com/protocol-buffers/docs/reference/java/com/google/protobuf/ByteString ): "immutable byte sequence. Substring is supported by sharing references to immutable underlying bytes, just like string

I don't know how bytestring is different from string or byte [] Can someone explain it? Thank you

Solution

You can think of bytestring as an array of immutable bytes Almost so. This is a byte [], which you can use in protobuf Protobuf does not allow you to use Java arrays because they are mutable

Bytestring exists because string is not suitable for representing arbitrary byte sequences Strings are used exclusively for character data

somewhat. If you call tobytearray(), you will get the same value, just as you call tobytestring() Tobytearray() Compare the implementation of the two methods in 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);
  }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>