Hessian源码学习(六)CollectionSerializer, MapSerializer

分析了BasicSerializer和JavaSerializer,剩下的序列化类就比较简单了,其实最本质的是基本类型的序列化 http://diaocow.iteye.com/blog/1317164,其他任何类型的序列化最后都可以回归到基本类型的序列化;

隐隐的感觉透着递归的理念,最后递归到一个基本问题的解决!

今天我们分析下CollectionSerializer和MapSerializer(参考源码版本3.0.13)。

1.CollectionSerializer
public void writeObject(Object obj, AbstractHessianOutput out)
    throws IOException
{
    Collection list = (Collection) obj;

    Class cl = obj.getClass();
    boolean hasEnd;
    
	// 输出集合头,格式:'Vt' [类型名] ['l'集合大小]  并且总是返回true
    if (cl.equals(ArrayList.class) || ! _sendJavaType)
      hasEnd = out.writeListBegin(list.size(), null);
    else
      hasEnd = out.writeListBegin(list.size(), obj.getClass().getName());

	// 循环序列化每一个集合元素
    Iterator iter = list.iterator();
    while (iter.hasNext()) {
      Object value = iter.next();
	  // 若不清楚这里面做了什么,请看Hessian源码学习(三)
      out.writeObject(value);
    }

	// 输出结束标记'z'
    if (hasEnd)
      out.writeListEnd();
}



2.MapSerializer
 public void writeObject(Object obj, AbstractHessianOutput out)
    throws IOException
  {
    if (out.addRef(obj))
      return;

    Map map = (Map) obj;

    Class cl = obj.getClass();
	// 输出Map头,格式:'Mt'[类型名] 
    if (cl.equals(HashMap.class))
      out.writeMapBegin(null);
    else
      out.writeMapBegin(obj.getClass().getName());

	// 循环序列化每一个键值对
    Iterator iter = map.entrySet().iterator();
    while (iter.hasNext()) {
      Map.Entry entry = (Map.Entry) iter.next();
	  
	  // 分别序列化键、值 (若不清楚这里面做了什么,请看Hessian源码学习(三))
      out.writeObject(entry.getKey());
      out.writeObject(entry.getValue());
    }
	// 输出结束标记'z'
    out.writeMapEnd();
  }


是不是很简单,我们以一个例子作为文章的结束:
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("key1", 100);
map.put("key2", 200);
map.put("key3", 300);

OutputStream os = new FileOutputStream("hessianOutput");
AbstractHessianOutput out = new HessianOutput(os);
out.setSerializerFactory(new SerializerFactory());
out.writeObject(map);


Hessian源码学习(六)CollectionSerializer, MapSerializer_第1张图片

总结

通过JavaSerializer, CollectionSerializer, MapSerializer我们可以看出,任何类型的序列化都可以回归到基本类型的序列化;

你可能感兴趣的:(java,hessian)