CAN YOU ACCESS THE PRIVATE METHOD FROM OUTSIDE THE CLASS?

Mayank Tripathi

Total Post:807

Points:4035
Posted by  Mayank Tripathi
 507  View(s)
Ratings:
Rate this:
  1. Mayank Tripathi

    Post:807

    Points:4035
    Can you access the private method from outside the class?

    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.

    Example:

    A. java

    public class A {  

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

    Method.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.setAccessible(true);  
        m.invoke(o, null);  
    }  

    Output:hello java

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!