Home > DeveloperSection > Interviews > Can you access the private method from outside the class?

Posted on    May-01-2015 12:45 AM

 Java Java  Reflection 
 1 Answer(s)
  361  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Posted on    May-01-2015 12:45 AM

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

Don't want to miss updates? Please click the below button!

Follow MindStick