«Back to Home

Core Java

Topics

How To Call Private Method From Another Class In Java

Call private method from another class
 
In Java, we can call the private method from outside the class through changing the runtime behaviour of the class and with the help of java.lang.Class and java.lang.reflect.Method classes. We can call private method from any other class.
 
Methods of Method class

public void setAccessible(boolean status) throws SecurityException

This method is used to set the accessibility of the method.
 
public Object invoke(Object method, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException

This method is used to call the method.
 
Method of Class class
 
public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException

This method is used to return a method object, which reflects the specific declared method of the class or an interface, represented by the class object.
 
Let's see an example to call private method from another class.
 
Code
  1. public class SimpleExample {  
  2.     private void message() {  
  3.         System.out.println("Private method calling...");  
  4.     }  
  5. }  
  1. import java.lang.reflect.Method;  
  2. public class CallMethodExample {  
  3.   
  4.     public static void main(String[] args) throws Exception {  
  5.         Class cl = Class.forName("SimpleExample");  
  6.         Object ob = cl.newInstance();  
  7.         Method m = cl.getDeclaredMethod("message"null);  
  8.         m.setAccessible(true);  
  9.         m.invoke(ob, null);  
  10.     }  
  11. }  
80

81
 
Let's see another example to call the parameterized private method from another class.
 
Code
  1. public class SimpleExample {  
  2.     private void cube(int a) {  
  3.         System.out.println(a * a * a);  
  4.     }  
  5. }  
  1. import java.lang.reflect.*;  
  2.   
  3. public class CallMethodExample {  
  4.     public static void main(String args[]) throws Exception {  
  5.         Class cl = SimpleExample.class;  
  6.         Object obj = cl.newInstance();  
  7.         Method msg = cl.getDeclaredMethod("cube"new Class[]{int.class});  
  8.         msg.setAccessible(true);  
  9.         msg.invoke(obj, 25);  
  10.     }  
  11. }  
  12.    
82

83

Output

84

Summary

Thus, we learnt that with the help of java.lang.Class and java.lang.reflect.Method classes, we can call private method from any other class and also learnt how to create it in Java.