-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathModifyingPrivateFields.java
More file actions
55 lines (46 loc) · 1.51 KB
/
ModifyingPrivateFields.java
File metadata and controls
55 lines (46 loc) · 1.51 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
package typeinfo;
import java.lang.reflect.*;
/**
* RUN:
* javac typeinfo/ModifyingPrivateFields.java && java typeinfo.ModifyingPrivateFields
* OUTPUT:
* i = 1, I'm totally safe, Am I save?
*
* f.getInt(pf) 1
* i = 47, I'm totally safe, Am I save?
*
* f.get(pf) I'm totally safe
* i = 47, I'm totally safe, Am I save?
*
* f.get(pf) Am I save?
* i = 47, I'm totally safe, No, you're not!
*/
public class ModifyingPrivateFields {
public static void main(String[] args) throws Exception {
WithPrivateFinalField pf = new WithPrivateFinalField();
System.out.println(pf);
Field f = pf.getClass().getDeclaredField("i");
f.setAccessible(true);
System.out.println("f.getInt(pf) " + f.getInt(pf));
f.setInt(pf, 47);
System.out.println(pf);
f = pf.getClass().getDeclaredField("s");
f.setAccessible(true);
System.out.println("f.get(pf) " + f.get(pf));
f.set(pf, "No, you're not!");
System.out.println(pf);
f = pf.getClass().getDeclaredField("s2");
f.setAccessible(true);
System.out.println("f.get(pf) " + f.get(pf));
f.set(pf, "No, you're not!");
System.out.println(pf);
}
}
class WithPrivateFinalField {
private int i = 1;
private final String s = "I'm totally safe";
private String s2 = "Am I save?";
public String toString() {
return "i = " + i + ", " + s + ", " + s2;
}
}