天天看點

Hessian序列化與反序列化對象Hessian序列化與反序列化對象

Hessian序列化與反序列化對象

package com.lius.DistributedProject.RPC.rpc_hessian;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.Serializable;

import com.caucho.hessian.io.HessianInput;
import com.caucho.hessian.io.HessianOutput;

/**
 * Hessian 序列化與反序列化
 * @author lius
 *
 */
public class seriableHessian implements Serializable{

	
	//序列化
	private byte[] seriableHessianFun(Object obj) throws IOException {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		HessianOutput ho = new HessianOutput(baos);
		ho.writeObject(obj);
		byte[] resultByte = baos.toByteArray();
		return resultByte;
	}
	
	//反序列化
	private Object reverseHessianFun(byte[] byteArray) throws IOException {
		ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
		HessianInput hi = new HessianInput(bais);
		Object resultObject = hi.readObject();
		return resultObject;
	}
	
	//apply
	public static void main(String[] args) throws IOException {
		new seriableHessian().start();
	}
	
	
	private void start() throws IOException {
		//執行個體化對象
		student stu = new student("tom", 19);
		stu.print();
		//序列化對象
		byte[] byteArray = seriableHessianFun(stu);
		//反序列化對象
		student obj = (student) reverseHessianFun(byteArray);
		obj.print();
	}
	
	
	class student implements Serializable{
		
		private String name;
		private int age;
		public student(String name, int age) {
			super();
			this.name = name;
			this.age = age;
		}
		@Override
		public String toString() {
			return "student [name=" + name + ", age=" + age + "]";
		}
		
		public void print() {
			System.out.println(toString());
		}
	}
	
	 
}