How to call private method from another class in java

You can call the private method from outside the class by changing the runtime behaviour of the class.

By the help of java.lang.Class class and java.lang.reflect.Method class, we can call private method from any other class.

Required methods of Method class

  1. public void setAccessible(boolean status) throws SecurityException sets the accessibility of the method.
  2. public Object invoke(Object method, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException is used to invoke the method.

Required methods of class

  1. public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException: eturns a Method object that reflects the specified declared method of the class or interface represented by this Class object.


Flash Soon


Copyright ©2017 Design& develop