一個例子弄懂invoke方法

 複製代碼
  1. import java.lang.reflect.Method;   
  2.   
  3. public class InvokeTester {   
  4.   
  5.  public int add(int param1, int param2) {   
  6.   return param1 + param2;   
  7.  }   
  8.   
  9.  public String echo(String mesg) {   
  10.   return "echo " + mesg;   
  11.  }   
  12.   
  13.  public static void main(String[] args) throws Exception {   
  14.   Class classType = InvokeTester.class;   
  15.   Object invokertester = classType.newInstance();   
  16.      
  17.   Method addMethod = classType.getMethod("add"new Class[] { int.class,   
  18.     int.class });   
  19.   //Method類的invoke(Object obj,Object args[])方法接收的參數必須爲對象,   
  20.   //如果參數爲基本類型數據,必須轉換爲相應的包裝類型的對象。invoke()方法的返回值總是對象,   
  21.   //如果實際被調用的方法的返回類型是基本類型數據,那麼invoke()方法會把它轉換爲相應的包裝類型的對象,   
  22.   //再將其返回   
  23.   Object result = addMethod.invoke(invokertester, new Object[] {   
  24.     new Integer(100), new Integer(200) });   
  25.   //在jdk5.0中有了裝箱 拆箱機制 new Integer(100)可以用100來代替,系統會自動在int 和integer之間轉換   
  26.   System.out.println(result);   
  27.   
  28.   Method echoMethod = classType.getMethod("echo",   
  29.     new Class[] { String.class });   
  30.   result = echoMethod.invoke(invokertester, new Object[] { "hello" });   
  31.   System.out.println(result);   
  32.  }   
  33. }  

轉自:http://wukunlsy.javaeye.com/blog/726747

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章