服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

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

今天做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);
   }