Home >Java >javaTutorial >How Can You Invoke Private Methods Using Reflection in Java?
Private Method Invocation through Reflection
In Java, direct reflection invocation of private methods is not permitted. However, there are alternative approaches to achieve this functionality.
Consider the following scenario where a method, initially defined as private, needs to be invoked through reflection:
Element node = outerNode.item(0); String methodName = node.getAttribute("method"); String objectName = node.getAttribute("object"); if ("SomeObject".equals(objectName)) object = someObject; else object = this; method = object.getClass().getMethod(methodName, (Class[]) null);
This code attempts to obtain a reference to the private method specified by the "methodName" attribute. However, this approach triggers a "NoSuchMethodException" because private methods are inaccessible via conventional reflection.
To overcome this limitation, we can utilize the getDeclaredMethod method:
Method method = object.getClass().getDeclaredMethod(methodName); method.setAccessible(true); Object r = method.invoke(object);
The getDeclaredMethod method retrieves a method regardless of its visibility. The setAccessible method allows us to bypass the private access restriction and invoke the method.
Cautions:
The above is the detailed content of How Can You Invoke Private Methods Using Reflection in Java?. For more information, please follow other related articles on the PHP Chinese website!