2015-09-07 11:44:36 -06:00
|
|
|
// typeinfo/ModifyingPrivateFields.java
|
2021-01-31 15:42:31 -07:00
|
|
|
// (c)2021 MindView LLC: see Copyright.txt
|
2015-11-15 15:51:35 -08:00
|
|
|
// We make no guarantees that this code is fit for any purpose.
|
2016-09-23 13:23:35 -06:00
|
|
|
// Visit http://OnJava8.com for more book information.
|
2015-06-15 17:47:35 -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?";
|
2021-01-31 15:42:31 -07:00
|
|
|
@Override public String toString() {
|
2015-06-15 17:47:35 -07:00
|
|
|
return "i = " + i + ", " + s + ", " + s2;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
public class ModifyingPrivateFields {
|
2016-01-25 18:05:55 -08:00
|
|
|
public static void
|
|
|
|
main(String[] args) throws Exception {
|
|
|
|
WithPrivateFinalField pf =
|
|
|
|
new WithPrivateFinalField();
|
2015-06-15 17:47:35 -07:00
|
|
|
System.out.println(pf);
|
|
|
|
Field f = pf.getClass().getDeclaredField("i");
|
|
|
|
f.setAccessible(true);
|
2017-01-20 21:30:44 -08:00
|
|
|
System.out.println(
|
|
|
|
"f.getInt(pf): " + f.getInt(pf));
|
2015-06-15 17:47:35 -07:00
|
|
|
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);
|
|
|
|
}
|
2015-09-07 11:44:36 -06:00
|
|
|
}
|
|
|
|
/* Output:
|
2015-06-15 17:47:35 -07:00
|
|
|
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!
|
2015-09-07 11:44:36 -06:00
|
|
|
*/
|