我看到可以将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存在,因为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); } }
原文地址:https://www.jb51.cc/java/126204.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。