aks*_*hay 2 java serialization
我怎样才能自己实现序列化.意思是我不希望我的类实现可序列化.但我想自己实现序列化.因此,如果不实现可序列化,我可以通过网络传输对象或将它们写入文件,然后在相同状态下检索它们.我想这样做,因为我想学习和探索事物.
序列化是将对象的结构转换为另一种格式的过程,该格式可以很容易地通过网络传输或者可以存储在文件中.Java将对象序列化为二进制格式.如果带宽/磁盘空间不是问题,则不需要这样做.您可以简单地将对象编码为XML:
// Code is for illustration purpose only, I haven't compiled it!!!
public class Person {
private String name;
private int age;
// ...
public String serializeToXml() {
StringBuilder xml = new StringBuilder();
xml.append("<person>");
xml.append("<attribute name=\"age\" type=\"int\">").append(age);
xml.append("</attribute>");
xml.append("<attribute name=\"name\" type=\"string\">").append(name);
xml.append("</attribute>");
xml.append("</person>");
return xml.toString();
}
Run Code Online (Sandbox Code Playgroud)
现在,您可以获取对象的XML表示形式,并将其"序列化"为文件或网络连接.用任何语言编写的可以解析XML的程序都可以将该对象"反序列化"为自己的数据结构.
如果您需要更紧凑的表示,您可以考虑二进制编码:
// A naive binary serializer.
public byte[] serializeToBytes() {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
// Object name and number of attributes.
// Write the 4 byte length of the string and the string itself to
// the ByteArrayOutputStream.
writeString("Person", bytes);
bytes.write(2); // number of attributes;
// Serialize age
writeString("age", bytes);
bytes.write(1); // type = 1 (i.e, int)
writeString(Integer.toString(age), bytes);
// serialize name
writeString("name", bytes);
bytes.write(2); // type = 2 (i.e, string)
writeString(name, bytes);
return bytes.toByteArray();
}
private static void writeString(String s, ByteArrayOutputStream bytes) {
bytes.write(s.length());
bytes.write(s.toBytes());
}
Run Code Online (Sandbox Code Playgroud)
要了解更紧凑的二进制序列化方案,请参阅Google Protocol Buffers的Java实现.