首页 > 其他 > 详细

如何(通过反射调用一个类的私有方法)

时间:2018-07-20 13:41:35      阅读:216      评论:0      收藏:0      [点我收藏+]
1 public class Calcu {
2 
3     private  int add(int a,int b) {
4         return a+b;
5     }
6 }
public class CalcuTest{

    public static void main(String[] args)   {
        Calcu ca=new Calcu();
        Class<Calcu> clazz=Calcu.class;
        Object res=null;
        try {
            //返回一个方法对象,
            Method m=clazz.getDeclaredMethod("add", new Class[] {Integer.TYPE,Integer.TYPE});
            m.setAccessible(false);//设置为true才能访问private
            res=m.invoke(ca, new Object[] {2,3});
        }catch(Exception e) {
            e.printStackTrace();
        }
        finally {
            System.out.println(res);
        }
    }
}

 

如何(通过反射调用一个类的私有方法)

原文:https://www.cnblogs.com/liamlee/p/9340799.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!