Thursday, January 24, 2008

Calling non-public methods

A very small and simple hack to call non-public methods in Java.

Problem
~~~~~~~
A non-public method of a class has to be called from another class. Both the classes are in different packages.

package apipackage;
public class APIClass {
void methodA() {
System.out.println("methodA Called");
}
}

package clientpackage;
public class ClientClass {
void methodACaller() {
...
...
...
}
}


Fill in the dotted lines to call methodA of APIClass.

Solution
~~~~~~~~
package clientpackage;
// import statements
public class ClientClass {
void methodACaller() {
apipackage.APIClass apiObject = new apipackage.APIClass();
Method methodA = apipackage.APIClass.class.getDeclaredMethod("methodA", null);
methodA.setAccessible(true); // this makes it possible to invoke methodA
methodA.invoke(apiObject, null);
}
}

One important thing to remember is to call "getDeclaredMethod" and not "getMethod" to obtain the Method object.

From Java docs:
"getMethod returns a Method object that reflects the specified public member method of the class"

/*
This would not work
Method methodA = apipackage.APIClass.class.getMethod("methodA", null);
*/