revised examples for chapter 9

This commit is contained in:
Luciano Ramalho
2014-10-20 18:53:56 -02:00
parent 812d416c15
commit ca049e9a3f
3 changed files with 185 additions and 25 deletions

View File

@@ -1,9 +1,8 @@
public class Confidential {
private String secret = "";
private String hidden = "burn after reading";
private String secret = "";
public Confidential(String text) {
this.secret = text.toUpperCase();
}
public Confidential(String text) {
secret = text.toUpperCase();
}
}

View File

@@ -2,24 +2,24 @@ import java.lang.reflect.Field;
public class Expose {
public static void main(String[] args) {
Confidential message = new Confidential("top secret text");
Field secretField = null;
try {
secretField = Confidential.class.getDeclaredField("secret");
}
catch (NoSuchFieldException e) {
System.err.println(e);
System.exit(1);
}
secretField.setAccessible(true); // break the lock!
try {
String wasHidden = (String) secretField.get(message);
System.out.println("message.secret = " + wasHidden);
}
catch (IllegalAccessException e) {
// this will not happen after setAcessible(true)
System.err.println(e);
}
}
public static void main(String[] args) {
Confidential message = new Confidential("top secret text");
Field secretField = null;
try {
secretField = Confidential.class.getDeclaredField("secret");
}
catch (NoSuchFieldException e) {
System.err.println(e);
System.exit(1);
}
secretField.setAccessible(true); // break the lock!
try {
String wasHidden = (String) secretField.get(message);
System.out.println("message.secret = " + wasHidden);
}
catch (IllegalAccessException e) {
// this will not happen after setAcessible(true)
System.err.println(e);
}
}
}