Java_Serializable(序列化)的理解和总结
Java Serializable(序列化)的理解和总结
1、序列化是干什么的?
简单说就是为了保存在内存中的各种对象的状态(也就是实例变量,不是方法),并且可以把保存的对象状态再读出来。虽然你可以用你自己的各种各样的方法来保存object states,但是Java给你提供一种应该比你自己好的保存对象状态的机制,那就是序列化。
2、什么情况下需要序列化
a)当你想把的内存中的对象状态保存到一个文件中或者数据库中时候;
b)当你想用套接字在网络上传送对象的时候;
c)当你想通过RMI传输对象的时候;
3、当对一个对象实现序列化时,究竟发生了什么?
在没有序列化前,每个保存在堆(Heap)中的对象都有相应的状态(state),即实例变量(instance ariable)比如:
Java代码
1. Foo myFoo = new Foo(); 2. myFoo .setWidth(37); 3. myFoo.setHeight(70); Foo myFoo = new Foo(); myFoo .setWidth(37); myFoo.setHeight(70);
1. FileOutputStream fs = new FileOutputStream("foo.ser"); 2. ObjectOutputStream os = new ObjectOutputStream(fs); 3. os.writeObject(myFoo); FileOutputStream fs = new FileOutputStream("foo.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(myFoo); 1. import java.io.*; 2. 3. 4. public class Box implements Serializable 5. { 6. private int width; 7. private int height; 8. 9. public void setWidth(int width){ 10. this.width = width; 11. } 12. public void setHeight(int height){ 13. this.height = height; 14. } 15. 16. public static void main(String[] args){ 17. Box myBox = new Box(); 18. myBox.setWidth(50); 19. myBox.setHeight(30); 20. 21. try{ 22. FileOutputStream fs = new FileOutputStream("foo.ser"); 23. ObjectOutputStream os = new ObjectOutputStream(fs); 24. os.writeObject(myBox); 25. os.close(); 26. }catch(Exception ex){ 27. ex.printStackTrace(); 28. } 29. } 30. 31. } import java.io.*; public class Box implements Serializable { private int width; private int height; public void setWidth(int width){ this.width = width; } public void setHeight(int height){ this.height = height; } public static void main(String[] args){ Box myBox = new Box(); myBox.setWidth(50); myBox.setHeight(30); try{ FileOutputStream fs = new FileOutputStream("foo.ser"); ObjectOutputStream os = new ObjectOutputStream(fs); os.writeObject(myBox); os.close(); }catch(Exception ex){ ex.printStackTrace(); } } }