exposing Java private fields with reflection

This commit is contained in:
Luciano Ramalho
2014-10-19 09:00:19 -02:00
parent 926bb370a0
commit 1d48cdbde5
11 changed files with 114 additions and 0 deletions

View File

@@ -0,0 +1,25 @@
import java.lang.reflect.Field;
public class AcessaPrivado {
public static void main(String[] args) {
ObjetoSecreto oSecreto = new ObjetoSecreto("senha super secreta");
Field campoPrivado = null;
try {
campoPrivado = ObjetoSecreto.class.getDeclaredField("escondido");
}
catch (NoSuchFieldException e) {
System.err.println(e);
System.exit(1);
}
campoPrivado.setAccessible(true); // arrombamos a porta
try {
String tavaEscondido = (String) campoPrivado.get(oSecreto);
System.out.println("oSecreto.escondido = " + tavaEscondido);
}
catch (IllegalAccessException e) {
// esta exceção nao acontece porque fizemos setAcessible(true)
System.err.println(e);
}
}
}