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