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): 我不清楚ByteString如何与String或byte []不同. 解决方法
您可以将ByteString视为不可变字节数组.几乎是这样这是一个字节[],您可以在protobuf中使用. Protobuf不允许您使用Java数组,因为它们是可变的.
ByteString存在,因为String不适合表示任意的字节序列.字符串专用于字符数据.
有点.如果你调用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); } } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |