Java 序列化和反序列化实例详解
Java序列化和反序列化实例详解
在分布式应用中,对象只有经过序列化才能在各个分布式组件之间传输,这就涉及到两个方面的技术-发送者将对象序列化,接受者将对象反序列化,下面就是一个很好的例子!
1.实体-Employee
importjava.io.Serializable; publicclassEmployeeimplementsSerializable{ /** * */ privatestaticfinallongserialVersionUID=1L; publicStringgetName(){ returnname; } publicvoidsetName(Stringname){ this.name=name; } publicintgetAge(){ returnage; } publicvoidsetAge(intage){ this.age=age; } privateStringname; privateintage; }
2.SerializeHelper
importjava.io.ByteArrayInputStream; importjava.io.ByteArrayOutputStream; importjava.io.IOException; importjava.io.ObjectInputStream; importjava.io.ObjectOutputStream; publicclassSerializeHelper{ publicbyte[]Serialize(Objectobject){ ByteArrayOutputStreambyteArrayOutputStream=newByteArrayOutputStream(); try{ ObjectOutputStreamobjectOutputStream=newObjectOutputStream(byteArrayOutputStream); //将对象写入到字节数组中进行序列化 objectOutputStream.writeObject(object); returnbyteArrayOutputStream.toByteArray(); }catch(IOExceptione){ e.printStackTrace(); } returnnull; } publicObjectdeSerialize(byte[]bytes){ //将二进制数组导入字节数据流中 ByteArrayInputStreambyteArrayInputStream=newByteArrayInputStream(bytes); try{ //将字节数组流转化为对象 ObjectInputStreamobjectInputStream=newObjectInputStream(byteArrayInputStream); returnobjectInputStream.readObject(); }catch(IOExceptione){ e.printStackTrace(); }catch(ClassNotFoundExceptione){ e.printStackTrace(); } returnnull; } }
3.测试类
publicclassHello{ /** *@paramargs */ publicstaticvoidmain(String[]args){ //TODOAuto-generatedmethodstub SerializeHelperserializeHelper=newSerializeHelper(); Employeeemployee=newEmployee(); employee.setName("admin"); employee.setAge(20); byte[]serializObject=serializeHelper.Serialize(employee); System.out.println(serializObject); Employeee=(Employee)serializeHelper.deSerialize(serializObject); System.out.println("Name:"+e.getName()+",Age:"+e.getAge()); } }
4.输出
[B@e05d173 Name:admin,Age:20
5.总结
序列化和反序列化还有其他的框架可以完成,比如Hession,有机会再研究!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!