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

Posted on    May-01-2015 12:45 AM

 Java Java  Reflection 
Ratings:
 1 Answer(s)
  371  View(s)
Rate this:

Mayank Tripathi
Mayank Tripathi

Total Post:807

Points:4035
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.

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


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

Follow MindStick