Java 序列化和反序列化实例详解
程序员文章站
2024-03-04 13:48:47
java 序列化和反序列化实例详解
在分布式应用中,对象只有经过序列化才能在各个分布式组件之间传输,这就涉及到两个方面的技术-发送者将对象序列化,接受者将对象反序列化,下...
java 序列化和反序列化实例详解
在分布式应用中,对象只有经过序列化才能在各个分布式组件之间传输,这就涉及到两个方面的技术-发送者将对象序列化,接受者将对象反序列化,下面就是一个很好的例子!
1.实体-employee
import java.io.serializable; public class employee implements serializable{ /** * */ private static final long serialversionuid = 1l; public string getname() { return name; } public void setname(string name) { this.name = name; } public int getage() { return age; } public void setage(int age) { this.age = age; } private string name; private int age; }
2.serializehelper
import java.io.bytearrayinputstream; import java.io.bytearrayoutputstream; import java.io.ioexception; import java.io.objectinputstream; import java.io.objectoutputstream; public class serializehelper { public byte[] serialize(object object) { bytearrayoutputstream bytearrayoutputstream = new bytearrayoutputstream(); try { objectoutputstream objectoutputstream = new objectoutputstream(bytearrayoutputstream); //将对象写入到字节数组中进行序列化 objectoutputstream.writeobject(object); return bytearrayoutputstream.tobytearray(); } catch (ioexception e) { e.printstacktrace(); } return null; } public object deserialize(byte[] bytes) { //将二进制数组导入字节数据流中 bytearrayinputstream bytearrayinputstream = new bytearrayinputstream(bytes); try { //将字节数组流转化为对象 objectinputstream objectinputstream = new objectinputstream(bytearrayinputstream); return objectinputstream.readobject(); } catch (ioexception e) { e.printstacktrace(); } catch (classnotfoundexception e) { e.printstacktrace(); } return null; } }
3.测试类
public class hello { /** * @param args */ public static void main(string[] args) { // todo auto-generated method stub serializehelper serializehelper = new serializehelper(); employee employee = new employee(); employee.setname("admin"); employee.setage(20); byte[] serializobject = serializehelper.serialize(employee); system.out.println(serializobject); employee e = (employee)serializehelper.deserialize(serializobject); system.out.println("name: " + e.getname()+",age: " + e.getage()); } }
4.输出
[b@e05d173 name: admin,age: 20
5.总结
序列化和反序列化还有其他的框架可以完成,比如hession,有机会再研究!
感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!