Sheldon Ross Sheldon Ross - 8 months ago 22
Java Question

Any way to Invoke a private method?

I have a class that uses XML and reflection to return

s to another class.

Normally these objects are sub fields of an external object, but occasionally it's something I want to generate on the fly. I've tried something like this but to no avail. I believe that's because Java won't allow you to access
methods for reflection.

Element node = outerNode.item(0);
String methodName = node.getAttribute("method");
String objectName = node.getAttribute("object");

if ("SomeObject".equals(objectName))
object = someObject;
object = this;

method = object.getClass().getMethod(methodName, (Class[]) null);

If the method provided is
, it fails with a
. I could solve it by making the method
, or making another class to derive it from.

Long story short, I was just wondering if there was a way to access a
method via reflection.


You can invoke private method with reflection. Modifying the last bit of the posted code:

Method method = object.getClass().getDeclaredMethod(methodName);
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).