java 反射機制 reflect

 1.獲取某個對象的Class,也就是.class,一般是通過如下兩種方式可以獲得。
     第一種方式:Class.forName("T"); T代表對象的名稱(包括該對象的包名),如:Class.forName  ("org.wsay.ttitfly.ReflectMethod");
    第二種方式:T.class 即可,T代表該對象名稱(不包括該對象的包名),如:ReflectMethod.class
   還有一種獨特的方式是專門針對int,long ..的包裝對象Integer,Long...的,如Integer.Type  表示基
   本類型 int 的 Class 實例
2, Method.invoke(Object o,Object...args),調用對象o的Method封裝的方法,參數爲args,args可以是個參數列表,也可以是個參數數組. 詳細見下面例子.
package org.wsay.ttitfly;
import java.lang.reflect.Method;
public class ReflectMethod {
 
 public static void main(String[] args)
 {
      try
      {
            Class rm = Class.forName("org.wsay.ttitfly.ReflectMethod"); //第一種方式獲取該對象的Class
            //Class rm = ReflectMethod.class;//第二種方式獲得
           //表示調用ReflectMethod的add方法,有2個int參數
           Method method = rm.getMethod("add", Integer.TYPE,Integer.TYPE);
           //   Object []o = new Object[2];
           //   o[0] = new Integer(2);
           //   o[1] = new Integer(3);
           Integer result = (Integer) method.invoke(new ReflectMethod(),2,3);//參數列表
          // Integer result = (Integer) method.invoke(new ReflectMethod(),o);//參數數組
          System.out.println(result.intValue());
       }
      catch (Exception e)
      {
            e.printStackTrace();
      }
 }
 public int add(int a,int b)
 {
        return a+b;
 }
}
打印結果爲:5

發佈了39 篇原創文章 · 獲贊 6 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章