为了账号安全,请及时绑定邮箱和手机立即绑定

How to call private method from another class in java

标签:
Java

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);  
  }
}  
点击查看更多内容
TA 点赞

若觉得本文不错,就分享一下吧!

评论

作者其他优质文章

正在加载中
JAVA开发工程师
手记
粉丝
2
获赞与收藏
70

关注作者,订阅最新文章

阅读免费教程

  • 推荐
  • 评论
  • 收藏
  • 共同学习,写下你的评论
感谢您的支持,我会继续努力的~
扫码打赏,你说多少就多少
赞赏金额会直接到老师账户
支付方式
打开微信扫一扫,即可进行扫码打赏哦
今天注册有机会得

100积分直接送

付费专栏免费学

大额优惠券免费领

立即参与 放弃机会
意见反馈 帮助中心 APP下载
官方微信

举报

0/150
提交
取消