现在的位置: 首页 > 综合 > 正文

通过反射调用其他类的private method

2014年02月25日 ⁄ 综合 ⁄ 共 1106字 ⁄ 字号 评论关闭

 今天做test case时遇到的一个问题。相信大家也会遇到。解决如下:
package ref;

public class Ref {
   public Ref() {
   }

   private void hehe(String aa) {
      System.out.println("--ref--------: " + aa);
   }

   public void hehe() {
      System.out.println("--ref-------hh-: ");
   }
}

--------class: TestRef------
package ref;

import java.lang.reflect.*;

public class TestRef {
   public TestRef() {
   }

   public static void main(String[] args0) throws Exception {
      System.setSecurityManager(null);
      Ref tr = new Ref();
      Class vv = tr.getClass();
      System.out.println("----------: " + System.getSecurityManager());

      Method[] methods = vv.getMethods();

      for(int i = 0; i < methods.length; i++) {
         System.out.println("----------: " + methods[i].getName());
      }

      Class worksheet = Class.forName("java.lang.String");
      Class[] args = new Class[1];
      args[0] = worksheet;
      Method method1 = vv.getMethod("hehe", null);

      method1.invoke(tr, null);

      Method method2 = vv.getDeclaredMethod("hehe", args);
      String[] sss = {"sssss"};
      method2.setAccessible(true);
      method2.invoke(tr, sss);
   }
}

抱歉!评论已关闭.