Skip to content

Instantly share code, notes, and snippets.

@gennad
Created December 2, 2010 18:52
Show Gist options
  • Save gennad/725843 to your computer and use it in GitHub Desktop.
Save gennad/725843 to your computer and use it in GitHub Desktop.
public class Secret {
private String secretCode = "It's a secret";
private String getSecretCode(){
return secretCode;
}
}
import java.lang.reflect.Field;
import java.lang.reflect.Method;
public class Hacker {
private static final Object[] EMPTY = {};
public void reflect() throws Exception {
Secret instance = new Secret();
Class secretClass = instance.getClass();
// Print all the method names & execution result
Method methods[] = secretClass.getDeclaredMethods();
System.out.println("Access all the methods");
for (int i = 0; i < methods.length; i++) {
System.out.println("Method Name: " + methods[i].getName());
System.out.println("Return type: " + methods[i].getReturnType());
methods[i].setAccessible(true);
System.out.println(methods[i].invoke(instance, EMPTY) + "\n");
}
// Print all the field names & values
Field fields[] = secretClass.getDeclaredFields();
System.out.println("Access all the fields");
for (int i = 0; i < fields.length; i++){
System.out.println("Field Name: " + fields[i].getName());
fields[i].setAccessible(true);
System.out.println(fields[i].get(instance) + "\n");
}
}
public static void main(String[] args){
Hacker newHacker = new Hacker();
try {
newHacker.reflect();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
//from http://en.wikibooks.org/wiki/Java_Programming/Reflection/Accessing_Private_Features_with_Reflection
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment