版权声明:本文为博主原创文章,转载请说明出处 https://blog.csdn.net/u010002184/article/details/86546285
1 maven
<!-- https://mvnrepository.com/artifact/com.caucho/hessian -->
<dependency>
<groupId>com.caucho</groupId>
<artifactId>hessian</artifactId>
<version>4.0.59</version>
</dependency>
2
public class Person implements Serializable {
private String name;
private Integer age;
//有无默认构造函数均能正常运行
// public Person() {
// }
public Person(String name, Integer age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
方法1 使用Serializable接口实现序列化
public static void main(String[] args) throws IOException, ClassNotFoundException {
// Person zhansan = new Person();//Person需要实现Serializable接口,不然报错
// zhansan.setName("高红程");
// zhansan.setAge(23);
Person zhansan = new Person("高红程", 22);//正常运行
//定义一个字节数组输出流
ByteArrayOutputStream os = new ByteArrayOutputStream();
//对象输出流
ObjectOutputStream out = new ObjectOutputStream(os);
//将对象写入到字节数组输出,进行序列化
out.writeObject(zhansan);
byte[] zhansanByte = os.toByteArray();
//字节数组输出流
ByteArrayInputStream is = new ByteArrayInputStream(zhansanByte);
//执行反序列化,从流中读取对象
ObjectInputStream in = new ObjectInputStream(is);
Person person = (Person) in.readObject();
System.out.println("姓名:" + person.getName());
System.out.println("年龄:" + person.getAge());
}
// 姓名:高红程
// 年龄:23
3 使用Hessian实现序列化
public static void main(String[] args) throws IOException {
Person zhansan = new Person();
zhansan.setName("高伟刚");
zhansan.setAge(22);
ByteArrayOutputStream os = new ByteArrayOutputStream();
//Hessian的序列化输出
HessianOutput ho = new HessianOutput(os);
ho.writeObject(zhansan);
byte[] zhansanByte = os.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(zhansanByte);
//Hessian的反序列化读取对象
HessianInput hi = new HessianInput(is);
Person person = (Person) hi.readObject();//前面的ho.writeObject(zhansan);必须有,不然报错HessianProtocolException: unknown code for readObject at end of file
System.out.println("姓名:" + person.getName());
System.out.println("年龄:" + person.getAge());
}
// 姓名:高伟刚
// 年龄:22
使用Hessian实现序列化的类,必须要实现Serializable接口,不然报错:
Exception in thread "main" java.lang.IllegalStateException: Serialized class com.weather.weatherexpert.common.model.Person must implement java.io.Serializable