readResolve()的使用

对于一些singleton class,如果你让其implements Serializable,会导致该class不再是singleton。使用ObjectInputStream.readObject()读取进来之后,如果是多次读取,就会创建多个object,下面的代码可以证明这一点,解决的办法之一就是override一个 method,readResolve()

 1 package foo;

 2 

 3 import java.io.FileInputStream;

 4 import java.io.FileOutputStream;

 5 import java.io.ObjectInputStream;

 6 import java.io.ObjectOutputStream;

 7 import java.io.Serializable;

 8 

 9 // Singleton Box:

10 class Box implements Serializable {

11     private static Box instance = new Box("TEST");

12     public static Box getInstance() {

13         return Box.instance;

14     }

15     private Box(String name) {  

16         this.name = name;

17     }

18     private String name;

19     @Override

20     public String toString() {

21         return "Box " + name;

22     }

23     

24     /* ********************************

25     private Object readResolve(    ) {

26         return Box.getInstance();

27     }

28     * ********************************/

29 }

30 

31 public class Foo {

32     public static void main(String[] args) {

33         Box box = Box.getInstance();

34         System.out.println(box.toString());   

35         try {   

36            ObjectOutputStream o = new ObjectOutputStream(   

37                         new FileOutputStream("e:/box.out"));   

38            o.writeObject(box);   

39            o.close();   

40         } catch(Exception e) {

41             e.printStackTrace();

42         }

43         

44         Box box1 = null, box2 = null;

45         

46         try {   

47            ObjectInputStream in =new ObjectInputStream(   

48                         new FileInputStream("e:/box.out"));

49            box1 = (Box)in.readObject();   

50            in.close();

51         } catch(Exception e) {

52             e.printStackTrace();

53         }

54         

55         try {   

56            ObjectInputStream in =new ObjectInputStream(   

57                         new FileInputStream("e:/box.out"));

58            box2 = (Box)in.readObject();   

59            in.close();

60         } catch(Exception e) {

61             e.printStackTrace();

62         }

63         

64         System.out.println("box1.equals(box2) : " + box1.equals(box2));

65         System.out.println(box1);

66         System.out.println(box2);  

67     }

68 }

 

 

你可能感兴趣的:(read)