Can you access the private method from outside the class?

Last updated:9/18/2020 3:46:17 PM

1 Answers

Mayank Tripathi
Mayank Tripathi

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.


A. java

public class A {  

  private void message(){System.out.println('hello java'); }

import java.lang.reflect.Method;  
public class MethodCall{  
public static void main(String[] args)throws Exception{  
    Class c = Class.forName('A');  
    Object o= c.newInstance();  
    Method m =c.getDeclaredMethod('message', null);  
    m.invoke(o, null);  

Output:hello java