欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Hessian序列化与反序列化对象

程序员文章站 2024-03-24 11:50:46
...

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());
		}
	}
	
	 
}

相关标签: JAVA java rpc