java中的反射,invoke方法

package org.curry.tool;
import java.lang.reflect.Method;
public class InvokeMethods {
 public static void main(String[] args) {
  Employee emp = new Employee();
  Class cl = emp.getClass();//是Class,而不是class
  // /getClass獲得emp對象所屬的類型的對象,Class就是類的類          
  // /Class是專門用來描述類的類,比如描述某個類有那些字段,          
  // /方法,構造器等等!
  try {
   // /getMethod方法第一個參數指定一個需要調用的方法名稱
   // /這裏是Employee類的setAge方法,第二個參數是需要調用 
   // 方法的參數類型列表,是參數類型!如無參數可以指定null 
   // /該方法返回一個方法對象 
   Method sAge = cl.getMethod("setAge", new Class[] { int.class });//參數必須和方法中一樣int和Integer,double和Double被視爲不同的類型
   Method gAge = cl.getMethod("getAge", null);
   Method pName = cl.getMethod("printName",
     new Class[] { String.class });
   
   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);
 }
}
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;
}

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