(轉)Java.lang.reflect.Method invoke方法 執行個體

來源:互聯網
上載者:User

標籤:color   return   cep   等等   方法   配置   exit   樣本   public   

背景:今天在項目中用到Method 的invoke方法,但是並不理解,查完才知道,原來如此!

import java.lang.reflect.Method;    /**  * Java.lang.reflect.Method invoke方法 執行個體  * 程式中設定檔中有對實體物件的get,set方法的描述,通過應用invoke()方法調用實體物件的method方法 return  * m_oGetter.invoke(oSrc, null); oSrc為實體物件,Method m_oGetter  * 這裡的m_oGetter是對應於在代理執行個體(oSrc)上調用的介面方法的 Method 執行個體,下面參考範例程式碼  *   */    class Employee {      // 定義一個員工類      public Employee() {          age = 0;          name = null;      }        // 將要被調用的方法      public void setAge(int a) {          age = a;      }        // 將要被調用的方法      public int getAge() {          return age;      }        // 將要被調用的方法      public void printName(String n) {          name = n;          System.out.println("The Employee Name is: " + name);      }        private int age;      private String name;  }    public class InvokeMethods {        public static void main(String[] args) {            Employee emp = new Employee();          Class<?> cl = emp.getClass();          // /getClass獲得emp對象所屬的類型的對象,Class就是類的類          // /Class是專門用來描述類的類,比如描述某個類有那些欄位,          // /方法,構造器等等!          try {                // /getMethod方法第一個參數指定一個需要調用的方法名稱              // /這裡是Employee類的setAge方法,第二個參數是需要調用              // 方法的參數類型列表,是參數類型!如無參數可以指定null              // /該方法返回一個方法對象              Method sAge = cl.getMethod("setAge", new Class[] { int.class });              Method gAge = cl.getMethod("getAge", null);              Method pName = cl.getMethod("printName",                      new Class[] { String.class });              /** *使用invoke調用指定的方法 */              Object[] args1 = { new Integer(25) };              // 參數列表              // emp為隱式參數該方法不是靜態方法必須指定              sAge.invoke(emp, args1);              Integer AGE = (Integer) gAge.invoke(emp, null);              int age = AGE.intValue();              System.out.println("The Employee Age is: " + age);              Object[] args3 = { new String("Jack") };              pName.invoke(emp, args3);          } catch (Exception e) {              e.printStackTrace();          }          System.exit(0);      }    }  

運行結果:

The Employee Age is: 25
The Employee Name is: Jack

 

(轉)Java.lang.reflect.Method invoke方法 執行個體

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.