2.8.2 序列化实例变量

序列化 普通对象数组对象 时,都用到了 serializeVariable 方法,其实现如下:

private static Element serializeVariable(Class<?> fieldType,
                                        Object fieldValue,
                                        Document target,
                                        Map<Object, String> table) {
  // transient 字段传入 null
  if (fieldValue == null) {
    return new Element("null");
  }
  if (fieldType.isPrimitive()) {  // 原始类型
    Element value = new Element("value");
    value.setText(fieldValue.toString());
    return value;
  } else {  // 对象引用
    Element reference = new Element("reference");
    if (table.containsKey(fieldValue)) {  // 该对象已经被序列化
      reference.setText(table.get(fieldValue).toString);
    } else {  // 未序列化
      reference.setText(Integer.toString(table.size()));
      serialize(fieldValue, target, table);
      return reference;
    }
  }
}

该方法存储变量的值,实现序列化。

  • 变量为 原始类型,则创建一个包含该变量值的 Element,并返回。
  • 变量为 对象引用,查询 table
    • 该对象已经被序列化过,则在 Element 中存储该对象在 table 中的唯一描述符值。
    • 未被序列化过,调用 serialize 序列化该对象。
  • 通过使用 table,可以:
    • 避免对 多次引用对象重复序列化
    • 避免在 循环引用 时陷入死循环。

results matching ""

    No results matching ""