Saturday, September 14, 2019

How to call private method from another class in java

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.

Required methods of Method class

1) public void setAccessible(boolean status) throws SecurityException sets the accessibility of the method.

2) public Object invoke(Object method, Object... args) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException is used to invoke the method.

Required method of Class class

1) public Method getDeclaredMethod(String name,Class[] parameterTypes)throws NoSuchMethodException,SecurityException: returns a Method object that reflects the specified declared method of the class or interface represented by this Class object.

Example of calling private method from another class

Let's see the simple example to call private method from another class.
File: A.java
  1. public class A {  
  2.   private void message(){System.out.println("hello java"); }  
  3. }  
File: MethodCall.java
  1. import java.lang.reflect.Method;  
  2. public class MethodCall{  
  3. public static void main(String[] args)throws Exception{  
  4.   
  5.     Class c = Class.forName("A");  
  6.     Object o= c.newInstance();  
  7.     Method m =c.getDeclaredMethod("message"null);  
  8.     m.setAccessible(true);  
  9.     m.invoke(o, null);  
  10. }  
  11. }  
Output:hello java

Another example to call parameterized private method from another class

Let's see the example to call parameterized private method from another class
File: A.java
  1. class A{  
  2. private void cube(int n){System.out.println(n*n*n);}  
  3. }  
File: M.java
  1. import java.lang.reflect.*;  
  2. class M{  
  3. public static void main(String args[])throws Exception{  
  4. Class c=A.class;  
  5. Object obj=c.newInstance();  
  6.   
  7. Method m=c.getDeclaredMethod("cube",new Class[]{int.class});  
  8. m.setAccessible(true);  
  9. m.invoke(obj,4);  
  10. }}  
Output:64

No comments:

Post a Comment

How to DROP SEQUENCE in Oracle?

  Oracle  DROP SEQUENCE   overview The  DROP SEQUENCE  the statement allows you to remove a sequence from the database. Here is the basic sy...