duansky'weblog

统计

留言簿(3)

友情链接

阅读排行榜

评论排行榜

如何通过反射调用其他类的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);
   }

}
 


转自:http://myrss.easyjf.com/html/20060901/3079097517061508.htm

posted on 2007-12-12 10:23 duansky 阅读(298) 评论(0)  编辑  收藏 所属分类: Java


只有注册用户登录后才能发表评论。


网站导航: