Created
April 8, 2015 21:45
-
-
Save benjholla/1a219f30397c2608065f to your computer and use it in GitHub Desktop.
An example of using Java Reflection to invoke a private API method
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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