背景:今天在項目中用到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