Any way to Invoke a private method?
You can invoke private method with reflection. Modifying the last bit of the posted code:
Method method = object.getClass().getDeclaredMethod(methodName);method.setAccessible(true);Object r = method.invoke(object);
There are a couple of caveats. First, getDeclaredMethod
will only find method declared in the current Class
, not inherited from supertypes. So, traverse up the concrete class hierarchy if necessary. Second, a SecurityManager
can prevent use of the setAccessible
method. So, it may need to run as a PrivilegedAction
(using AccessController
or Subject
).
Use getDeclaredMethod()
to get a private Method object and then use method.setAccessible()
to allow to actually call it.
If the method accepts non-primitive data type then the following method can be used to invoke a private method of any class:
public static Object genericInvokeMethod(Object obj, String methodName, Object... params) { int paramCount = params.length; Method method; Object requiredObj = null; Class<?>[] classArray = new Class<?>[paramCount]; for (int i = 0; i < paramCount; i++) { classArray[i] = params[i].getClass(); } try { method = obj.getClass().getDeclaredMethod(methodName, classArray); method.setAccessible(true); requiredObj = method.invoke(obj, params); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } return requiredObj; }
The Parameter accepted are obj, methodName and the parameters. For example
public class Test {private String concatString(String a, String b) { return (a+b);}}
Method concatString can be invoked as
Test t = new Test(); String str = (String) genericInvokeMethod(t, "concatString", "Hello", "Mr.x");