How to call private method from another class in Java with help of Reflection API?

We can call the private method of a class from another class in Java (which are defined using the private access modifier in Java).

We can do this by changing the runtime behavior of the class by using some predefined methods of Java. For accessing private method of different class we will use Reflection API.

To call the private method, we will use following methods of Java.lang.class and Java.lang.reflect.Method

  • Method[] getDeclaredMethods(): This method returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.
  • setAccessible(): Set the accessible flag for this object to the indicated boolean value. A value of true indicates that the reflected object should suppress Java language access checking when it is used. A value of false indicates that the reflected object should enforce Java language access checks.
  • invoke():It invokes the underlying method represented by this Method object, on the specified object with the specified parameters.