/** @param object May be null if mayBeNull is true.
- @return true if no bytes need to be written for the object. */
boolean writeReferenceOrNull (Output output, Object object, boolean mayBeNull) { // @1
if (object == null) { // @2
if (TRACE || (DEBUG && depth == 1)) log(“Write”, null);
output.writeVarInt(Kryo.NULL, true);
return true;
}
if (!referenceResolver.useReferences(object.getClass())) { // @3
if (mayBeNull) output.writeVarInt(Kryo.NOT_NULL, true);
return false;
}
// Determine if this object has already been seen in this object graph.
int id = referenceResolver.getWrittenId(object); // @4
// If not the first time encountered, only write reference ID.
if (id != -1) { // @5
if (DEBUG) debug(“kryo”, "Write object reference " + id + ": " + string(object));
output.writeVarInt(id + 2, true); // + 2 because 0 and 1 are used for NULL and NOT_NULL.
return true;
}
// Otherwise write NOT_NULL and then the object bytes.
id = referenceResolver.addWrittenObject(object); // @6
output.writeVarInt(NOT_NULL, true);
if (TRACE) trace(“kryo”, "Write initial object reference " + id + ": " + string(object));
return false; // @7
}
代码@1:参数说明:Output output:输出流;Object object:待序列化的对象;
代码@2:如果对象为空,写入Kryo.NULL(0),然后返回true,表示需要设置generic,后续会讲解一下generic(泛型支持)。
代码@3:如果是基本类型,如果maybe(值可能为空),但该方法不为空,则设置为Kryo.NOT_NULL,然后返回false,表示非引用类型,需要持久化值。
代码@4:判断该对象是否在对象图中已被序列化一次。(其实现方式ListReferenceResolver、MapReferenceResolver)。
ListReferenceResolver#getWrittenId
public int getWrittenId (Object object) {
for (int i = 0, n = seenObjects.size(); i < n; i++) {
if (seenObjects.get(i) == object) {
return i;
}
}
return -1;
}
代码@5:如果writtenId不等于-1,表示该对象已被序列化,直接序列化ID,直接返回true,然后结束writeClassAndObject该方法,表示该对象实例完成。
代码@6:为object构建一个ID,这个ID数据是在一次嵌套调用writeClassAndObjec