/**
* Return all classes that may be wrapped. Subclasses should implement this
* to return a constant array of classes.
*/
abstract protected Class<? extends Writable>[] getTypes();
GenericWritable有4个属性
/**
* Set the instance that is wrapped.
*
* @param obj
*/
public void set(Writable obj) {
instance = obj;//对实例赋值
Class<? extends Writable> instanceClazz = instance.getClass();//获得实例的类型
Class<? extends Writable>[] clazzes = getTypes();//获取事先配置的类型数组
//查找实例类型在类型数组中的序号
for (int i = 0; i < clazzes.length; i++) {
Class<? extends Writable> clazz = clazzes;
if (clazz.equals(instanceClazz)) {
type = (byte) i;//设置type的值(序号)
return;
}
}
throw new RuntimeException("The type of instance is: "
+ instance.getClass() + ", which is NOT registered.");
}
序列化方法write
@Override
public void write(DataOutput out) throws IOException {
if (type == NOT_SET || instance == null)
throw new IOException("The GenericWritable has NOT been set correctly. type="
+ type + ", instance=" + instance);
out.writeByte(type);//将类型序号虚拟化
instance.write(out);//序列化实例对象
}
反序列化: