JAVA序列化/反序列化与单例

单例设计类:

 

Java代码   收藏代码
  1. package com.test.singleton;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.ObjectStreamException;  
  5. import java.io.Serializable;  
  6.   
  7.   
  8. public class SingleTon implements Serializable{  
  9.   
  10.     /** 
  11.      *  
  12.      */  
  13.     private static final long serialVersionUID = 768457893059530646L;  
  14.   
  15.     private SingleTon(){  
  16.         System.out.println("here...");  
  17.         //避免反射机制,导致的多例问题,通过反射机制仍然可以对私有构造函数进行操作  
  18.         if(instance != null){  
  19.             return;  
  20.         }  
  21.     }  
  22.       
  23.     private static final SingleTon instance = new SingleTon();  
  24.       
  25.     public static SingleTon getInstance(){  
  26.         return instance;  
  27.     }  
  28.       
  29.     public void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{  
  30.         //  
  31.     }  
  32.     /** 
  33.      * 严格单例,确保remote instance不会干扰单例模式,避免在发序列化过程中对单例的影响. 
  34.      * @return 
  35.      * @throws ObjectStreamException 
  36.      */  
  37.     public Object readResolve() throws ObjectStreamException{  
  38.         return instance;  
  39.     }  
  40. }  

 

Java代码   收藏代码
  1. ///////////流方式:  
  2. package com.test.singleton;  
  3.   
  4. import java.io.File;  
  5. import java.io.FileInputStream;  
  6. import java.io.FileOutputStream;  
  7. import java.io.ObjectInputStream;  
  8. import java.io.ObjectOutputStream;  
  9.   
  10. public class SerializeCheckMain {  
  11.   
  12.     /** 
  13.     * @param args 
  14.     */  
  15.     public static void main(String[] args) throws Exception{  
  16.         // TODO Auto-generated method stub  
  17.         SingleTon s1 = SingleTon.getInstance();  
  18.         File file = new File("D:\\singleTome.txt");  
  19.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));  
  20.         oos.writeObject(s1);  
  21.         oos.close();  
  22.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream(file));  
  23.         SingleTon s2 = (SingleTon)ois.readObject();  
  24.         System.out.println("HashCode 1 : " + s1.hashCode());  
  25.         System.out.println("HashCode 2 : " + s2.hashCode());  
  26.         System.out.println("Equal : " + (s1 == s2));//打破单例  
  27.     }  
  28.   
  29. }  

 

 

 

Java代码   收藏代码
  1. //////////////////////反射方式:  
  2. package com.test.singleton;  
  3.   
  4. import java.lang.reflect.Constructor;  
  5.   
  6. /** 
  7.  * @author liuguanqing 
  8.  *  反射机制,测试单例 
  9.  */  
  10. public class RefletCheckMain {  
  11.   
  12.     /** 
  13.     * @param args 
  14.     */  
  15.     public static void main(String[] args) throws Exception{  
  16.         SingleTon s1 = SingleTon.getInstance();  
  17.         Constructor[] constructors = SingleTon.class.getDeclaredConstructors();  
  18.         Constructor<SingleTon> c = constructors[0];  
  19.         c.setAccessible(true);  
  20.         SingleTon s2 = c.newInstance(null);  
  21.         System.out.println("HashCode 1 : " + s1.hashCode());  
  22.         System.out.println("HashCode 2 : " + s2.hashCode());  
  23.         System.out.println("Equal : " + (s1 == s2));//打破单例  
  24.     }  
  25.   
  26. }  

 

注意,序列化和反序列化,是java使用字节码技术生成对象,将不会执行构造器方法.

注意到在writeReplace和readResolve,我们可以严格控制singleton的对象,在同一个JVM中完完全全只有唯一的对象,控制不让singleton对象产生副本.

 

Java代码   收藏代码
  1. package com.test.main;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.ObjectInputStream;  
  7. import java.io.ObjectOutputStream;  
  8. import java.io.ObjectStreamException;  
  9. import java.io.Serializable;  
  10.   
  11. public class TestSerializable implements Serializable{  
  12.   
  13.     /** 
  14.      *  
  15.      */  
  16.     private static final long serialVersionUID = -1740221592194879964L;  
  17.   
  18.     private Integer age;  
  19.       
  20.     private String name;  
  21.       
  22.     public TestSerializable(){  
  23.         System.out.println("Contrustor..");  
  24.     }  
  25.       
  26.     public Integer getAge() {  
  27.         return age;  
  28.     }  
  29.   
  30.   
  31.     public void setAge(Integer age) {  
  32.         this.age = age;  
  33.     }  
  34.   
  35.   
  36.     public String getName() {  
  37.         return name;  
  38.     }  
  39.   
  40.   
  41.     public void setName(String name) {  
  42.         this.name = name;  
  43.     }  
  44.       
  45.     private void writeObject(java.io.ObjectOutputStream out) throws IOException{  
  46.         System.out.println("writeObject");  
  47.         out.writeInt(this.age);  
  48.         out.writeInt(this.name.getBytes("utf8").length);  
  49.         out.write(this.name.getBytes("utf8"));  
  50.     }  
  51.       
  52.     private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException{  
  53.         this.age = in.readInt();  
  54.         int chars = in.readInt();  
  55.         byte[] bytes = new byte[chars];  
  56.         in.readFully(bytes);  
  57.         this.name = new String(bytes,"utf8");  
  58.         System.out.println("readObject");  
  59.     }  
  60.       
  61.     public Object readResolve() throws ObjectStreamException{  
  62.         System.out.println("readResolve");  
  63.         return this;  
  64.     }  
  65.       
  66.     public Object writeReplace() throws ObjectStreamException{  
  67.         System.out.println("writeReplace");  
  68.         return this;  
  69.     }  
  70.   
  71.   
  72.     /** 
  73.      * @param args 
  74.      */  
  75.     public static void main(String[] args) throws Exception{  
  76.         ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D:\\sss.txt"));  
  77.         TestSerializable ss = new TestSerializable();  
  78.         ss.setAge(12);  
  79.         ss.setName("zhangsan");  
  80.         oos.writeObject(ss);  
  81.         oos.close();  
  82.         ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D:\\sss.txt"));  
  83.         TestSerializable ss2 = (TestSerializable)ois.readObject();  
  84.         System.out.println(ss == ss2);  
  85.         System.out.println(ss2.getName());  
  86.         ois.close();  
  87.         //////////执行结果  
  88.         //Contrustor..  
  89.         //writeReplace  
  90.         //writeObject  
  91.         //readObject  
  92.         //readResolve  
  93.         //false  
  94.         //zhangsan  
  95.           
  96.     }  
  97.   
  98. }  

 

Java代码   收藏代码
  1. //////////Externalizable接口是Serializable的子接口,不过此接口提供了两个特殊的扩展方法:  
  2.     @Override  
  3.     public void writeExternal(ObjectOutput out) throws IOException {  
  4.         System.out.println("writeEx");  
  5.         out.writeInt(50);  
  6.           
  7.     }  
  8.   
  9.     @Override  
  10.     public void readExternal(ObjectInput in) throws IOException,  
  11.             ClassNotFoundException {  
  12.         System.out.println("readEx");  
  13.         this.age = in.readInt();  
  14.     }  

 

 

注意实现Externalizable接口的类,在发序列化时,将会执行构造函数,因为对于流操作而言,此对象是有明确类型的(Serializable接口是个标记接口).

而且,如果实现了writeExternal和readExternal,将不会在执行readObject和writeObject,因为此时这两个方法已经被"擦除".

 

对于java序列化和反序列化,被序列化的类中有关于serialVersionUID会带来一些问题;

1) 如果你调整了Class结构(比如新增/去除某个属性值,但是不能引入编译错误),但没有修改serialVersionUID;那么在反序列化和序列化时不会带来异常,只是可能导致部分属性在get时为null.

2) 如果你调整了Class结构,同时也修改了serialVersionUID;如果序列化和反序列双方没有保持uid一致的话,将会直接导致反序列化异常.(java.io.InvalidClassException)

3) 如果你没有显式的声明serialVersionUID,那么对于JVM而言,不同的class类结构(属性列表和方法列表)将会得出不同的uid;因此如果序列化双方不能保持一致的uid,仍然会带来问题.

 

本文转载自http://shift-alt-ctrl.iteye.com/blog/1842040

猜你喜欢

转载自wely.iteye.com/blog/2228826