java利用反射来调用一个类的私有方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java利用反射来调用一个类的私有方法相关的知识,希望对你有一定的参考价值。

public class Calculator2{
 
     private int add(int a,int b){
          
         return a+b;
     }
     
}
public class Test {
    public static void main(String[] args){
             Calculator2 calculator2 = new Calculator2();
             Class<Calculator2> clazz = Calculator2.class;
             Object result = null;
             try{
             Method method = clazz.getDeclaredMethod("add", new Class[]{Integer.TYPE,Integer.TYPE});
             method.setAccessible(true);
             result =  method.invoke(calculator2, new Object[]{2,3});            
             }catch (Exception e) {
             e.printStackTrace();
            }finally{              
              System.out.println(result); 
              }        
    }
}

 

以上是关于java利用反射来调用一个类的私有方法的主要内容,如果未能解决你的问题,请参考以下文章