We can call the private method of a class from another class in Java using Reflection API.
- getDeclaredMethod return a method that reflect to specify in class and represent by Class object.
- invoke() method call the type of object and pass the parameter when we want to invoke.
- demo() method name we want to call from getDeclaredMethod.
- Class[] declare the parameters that method take when we want to execute.
Syntax :- public void setAccessible(boolean status) throws Exception
public Object invoke(Object method, Object… args) throws IllegalAccessException
import java.lang.reflect.Method;
class Hello {
private void demo(String str) {
System.out.println("welcome to java " + str);
}
}
public class PrivateMethodTest {
public static void main(String[] args) throws Exception {
Class c = Hello.class;
Object p = c.newInstance();
Method m = c.getDeclaredMethod("demo", new Class[] { String.class });
m.setAccessible(true);
m.invoke(p, "collection");
}
}
Output :-
welcome to java collection