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
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