Are You Feeling any difficulity while writing Core-Java Programs. Send those to me Here.

Monday, 24 June 2013

Is it possible to access private methods in other classes?? Ans: Yes

Yes. If the class is public and the method is declared as private we can access that type of private methods in other classes by modifying the access in run time.

Example:

public class A{
 private void message(){
System.out.println("Hello User, I am in private method");

    }
}

save above file as A.java

public class Mainclass{
public static void main(String arg[]){
Class c = Class.forName("A");   // A is class name of above class
Object o = c.newInstance();  // Create object for the above class
Method m = c.getDeclaredMethod("message", null);  // get the private method
m.setAccessible(true);  // modify the access to the private method
m.invoke(o, null); // Invoke private method in other class
}
}

Save above file as Mainclass.java, compile and run it.
Output: Hello User, I am in private method

No comments:

Post a Comment