Hessian1.0

public static byte[] Serialize(Object o) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        HessianOutput hessianOutput = new HessianOutput(byteArrayOutputStream);
        hessianOutput.writeObject(o);

        return byteArrayOutputStream.toByteArray();
    }

public static Object Deserialize(byte[] bytes) throws IOException {
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

        HessianInput hessianInput = new HessianInput(byteArrayInputStream);
        return hessianInput.readObject();
    }

一个类

static class User implements Serializable {
        public int age;
        public String name;

        public User(int age, String name){
            this.age = age;
            this.name = name;
        }
}

序列化和反序列化

User user = new User(20, "nivia");
byte[] ser = Serialize(user);

User deser = (User)Deserialize(ser);
System.out.println(deser.name);//nivia

Hessian1.0源码分析

序列化

HessianOutput#writeObject方法

Untitled

如果是null对象,直接调用writeNull方法,向流中写入信息后返回

首先是获取Serializer对象,_serializerFactory是一个SerializerFactory,默认通过SerializerFactory.createDefault方法创建该对象,跟进其getSerialize方法,方法会传入对象对应Class对象

方法下会在一个Map缓存中查找,是否序列化过对应类型的对象,如果有则返回对应Serializer对象

否则通过loadSerializer方法获取,最后将获取到的Serializer对象加进Map缓存

在loadSerializer方法中,首先会调用ContextSerializerFactory#getSerializer方法

Untitled

向_serializerClassMap中查找,是否是一些基本类型的对象

Untitled

随后会判断类型是否是一些定制的类型

都没有成功serializer的话会经过一系列判断,根据类型返回对应serializer对象