Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An example of using Java Reflection to invoke a private API method
import java.lang.reflect.Method;
import java.util.Random;
public class PrivateMethodReflection {
public static void main(String[] args) throws Exception {
Person person = new Person("Bob");
System.out.println("Name: " + person.getName());
// call the private getID method get a reference to the Person class
Class personClass = person.getClass();
// get a reference to the private method
Method getIDMethod = personClass.getDeclaredMethod("getID");
// make the private method accessible
// (if you skip this step you get a IllegalAccessException)
getIDMethod.setAccessible(true);
// getID() method has no parameters so create an empty object
// array to pass for params
Object[] noparams = new Object[] {};
// invoke the getID method and cast the result to a Long return type
// since the result is a long
long id = (Long) getIDMethod.invoke((Object) person, noparams);
System.out.println("ID: " + id);
}
public static class Person {
private String name;
private long id;
public Person(String name) {
this.name = name;
Random rnd = new Random();
id = rnd.nextLong();
}
public String getName() {
return name;
}
// ///////// PRIVATE /////////////
private long getID() {
return id;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.