-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSingletonePreventSerialization.java
More file actions
58 lines (45 loc) · 1.33 KB
/
Copy pathSingletonePreventSerialization.java
File metadata and controls
58 lines (45 loc) · 1.33 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package Misc;
// Java code to remove the effect of
// Serialization on singleton classes
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Singleton implements Serializable {
// public instance initialized when loading the class
public static Singleton instance = new Singleton();
private Singleton()
{
// private constructor
}
// implement readResolve method
protected Object readResolve() { return instance; } //override the read resolve function to prevent the Serialization.
}
public class SingletonePreventSerialization {
public static void main(String[] args)
{
try {
Singleton instance1 = Singleton.instance;
ObjectOutput out = new ObjectOutputStream(
new FileOutputStream("file.text"));
out.writeObject(instance1);
out.close();
// deserialize from file to object
ObjectInput in = new ObjectInputStream(
new FileInputStream("file.text"));
Singleton instance2
= (Singleton)in.readObject();
in.close();
System.out.println("instance1 hashCode:- "
+ instance1.hashCode());
System.out.println("instance2 hashCode:- "
+ instance2.hashCode());
}
catch (Exception e) {
e.printStackTrace();
}
}
}