Example & Tutorial understanding programming in easy ways.

How to access private metod using Reflection in Java?

Accessing Private Methods

To access a private method call the Class.getDeclaredMethod(String name, Class[] parameterTypes) or Class.getDeclaredMethods() method. The methods Class.getMethod(String name, Class[] parameterTypes) and Class.getMethods() methods only return public methods, so they won't work. Here is a simple example of a class with a private method, and below that the code to access that method via Java Reflection

public class PrivateObject {

private String privateString = null;

public PrivateObject(String privateString) {

this.privateString = privateString;

}

private String getPrivateString(){

return this.privateString;

}

}

PrivateObject privateObject = new PrivateObject("The Private Value");

Method privateStringMethod = PrivateObject.class.getDeclaredMethod("getPrivateString", null);

privateStringMethod.setAccessible(true);

String returnValue = (String)

privateStringMethod.invoke(privateObject, null);

System.out.println("returnValue = " + returnValue);

Read More →