In Java, a `private` method is only accessible within the class in which it is declared. This means it cannot be accessed directly from outside the class, not even by subclasses. However, the method can be invoked internally by other methods within the same class.
How to Invoke a Private Method:
A `private` method can be invoked directly by any other method inside the same class. Here is how it works:
- Direct Invocation Inside the Class:
- You can call a `private` method from any non-static or static method within the same class.
- The method call follows the same syntax as any other method, but it must be within the same class.
Example:
class MyClass {
// Private method
private void displayMessage() {
System.out.println("Hello from a private method!");
}
// Public method that calls the private method
public void callPrivateMethod() {
displayMessage(); // Private method invoked here
}
}
public class Main {
public static void main(String[] args) {
MyClass obj = new MyClass();
obj.callPrivateMethod(); // indirectly calls the private method
}
}
Explanation:
- The `displayMessage()` method is `private`, so it cannot be accessed directly from outside `MyClass`.
- However, within `MyClass`, the `callPrivateMethod()` public method invokes `displayMessage()`.
- When you create an object of `MyClass` and call `callPrivateMethod()`, it indirectly triggers the execution of the `private` method `displayMessage()`.
Summary:
A `private` method can be invoked directly by other methods within the same class. To expose the functionality of a `private` method indirectly, you can create a public or protected method that calls the `private` method internally.
You can invoke a private method with reflection. Modifying the last bit of the posted code:
method = object.getClass().getDeclaredMethod(methodName);
method.setAccessible(true);
Object r = method.invoke(object);
There are a few elements that need to be observed when using this method. First, getDeclaredMethod will only find the method declared in the current Class, not inherited from supertypes. Traverse up the concrete class hierarchy if necessary.
Second, a SecurityManager can prevent use of the setAccessible method. It may need to run as a PrivilegedAction (using AccessController or Subject).