2015-04-20 15:36:01 -07:00
|
|
|
|
//: typeinfo/ModifyingPrivateFields.java
|
2015-05-29 14:18:51 -07:00
|
|
|
|
// <20>2015 MindView LLC: see Copyright.txt
|
2015-04-20 15:36:01 -07:00
|
|
|
|
import java.lang.reflect.*;
|
|
|
|
|
|
|
|
|
|
class WithPrivateFinalField {
|
|
|
|
|
private int i = 1;
|
|
|
|
|
private final String s = "I'm totally safe";
|
|
|
|
|
private String s2 = "Am I safe?";
|
2015-05-05 11:20:13 -07:00
|
|
|
|
@Override
|
2015-04-20 15:36:01 -07:00
|
|
|
|
public String toString() {
|
|
|
|
|
return "i = " + i + ", " + s + ", " + s2;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
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);
|
|
|
|
|
}
|
|
|
|
|
} /* Output:
|
|
|
|
|
i = 1, I'm totally safe, Am I safe?
|
|
|
|
|
f.getInt(pf): 1
|
|
|
|
|
i = 47, I'm totally safe, Am I safe?
|
|
|
|
|
f.get(pf): I'm totally safe
|
|
|
|
|
i = 47, I'm totally safe, Am I safe?
|
|
|
|
|
f.get(pf): Am I safe?
|
|
|
|
|
i = 47, I'm totally safe, No, you're not!
|
|
|
|
|
*///:~
|