继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

How to call private method from another class in java

LearningForever
关注TA
已关注
手记 6
粉丝 2
获赞 70

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.


Example of calling private method from another class

Let's see the simple example to call private method from another class.

public class A {  
  private void message(){System.out.println("hello 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);  
}  
}  

Another example to call parameterized private method from another class

Let's see the example to call parameterized private method from another class

class A{  
  private void cube(int n){System.out.println(n*n*n);}  
}  
import java.lang.reflect.*;  
class M{  
  public static void main(String args[])throws Exception{  
    Class c=A.class;  
    Object obj=c.newInstance();  

    Method m=c.getDeclaredMethod("cube",new Class[]{int.class});  
    m.setAccessible(true);  
    m.invoke(obj,4);  
  }
}  
打开App,阅读手记
0人推荐
发表评论
随时随地看视频慕课网APP