/**
* Invokes a private method on a class or object. This method
* can invoke static methods on classes, and instance methods
* on objects.
*
* When invoking an instance method, the instance of the object
* must be passed as the first parameter. For static methods,
* this parameter can be null.
*
* @param object the object to invoke the method on (this is
* only applicable for instance methods, can be null
* for static methods).
* @param clazz the class of object.
* @param methodName the name of the method to invoke.
* @param parameters parameters passed to the method.
* @return result from the method or null if method returns void.
*/
public static Object invokePrivateMethod(Object object,
Class clazz,
String methodName,
Object... parameters) {
// build an array of parameter types
Class[] params = new Class[parameters.length];
for (int i = 0; i < parameters.length; i++) {
params[i] = parameters[i].getClass();
}
Object result = null;
// try to execute the method
try {
Method method = clazz.getDeclaredMethod(methodName, params);
method.setAccessible(true);
// are we invoking a static method or an instance method?
if (object != null) {
result = method.invoke(object, parameters);
} else {
result = method.invoke(clazz, parameters);
}
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public class Greeter {
// a private instance member
private String name;
// public constructor
public Greeter(String name) {
this.name = name;
}
// static method that responds with a cheery greeting
private static String sayHello(String name) {
return "Hello " + name;
}
// instance method that responds with a cheery greeting
private String sayHello() {
return "Hello " + this.name;
}
}
invokePrivateMethod() that we defined earlier we can invoke these methods as follows.
// invoke a static method
invokePrivateMethod(null, Greeter.class, "sayHello", "Shane");
// invoke an instance method
Greeter greeter = new Greeter("Shane");
invokePrivateMethod(greeter, greeter.getClass(), "sayHello");
October 2005 November 2005 December 2005 January 2006 March 2006 May 2006 August 2006 September 2006 October 2006 November 2006 May 2007
Subscribe to Posts [Atom]