java對過反射調用方法

 
public class InvokeTester {
    public InvokeTester() {
    }

    String str;

    public InvokeTester(String str) {
        this.str = str;
    }

    public int add(int param1, int param2) {
        return param1 + param2;
    }

    public String echo(String msg) {
        return "echo: " + msg;
    }

    public String getStr() {
        return "one param ctor" + str;
    }

    public static void main(String[] args) throws Exception {
        //直接獲取類
        //Class<?> classType = InvokeTester.class;
        //經過完整的類型路徑獲取類
        Class<?> classType = Class.forName("com.top.utils.InvokeTester");
        //使用newInstance建立對象
        // Object invokeTester = classType.newInstance();
        //使用默認構造函數獲取對象
        Object invokeTester = classType.getConstructor(new Class[]{}).newInstance(new Object[]{});
        //獲取InvokeTester類的add()方法
        Method addMethod = classType.getMethod("add", new Class[]{int.class, int.class});
        //調用invokeTester對象上的add()方法
        Object result = addMethod.invoke(invokeTester, new Object[]{new Integer(100), new Integer(200)});
        System.out.println((Integer) result);
        //獲取InvokeTester類的echo()方法
        Method echoMethod = classType.getMethod("echo", new Class[]{String.class});
        //調用invokeTester對象的echo()方法
        result = echoMethod.invoke(invokeTester, new Object[]{"Hello"});
        System.out.println((String) result);
        //建立有參構造函數的類對象
        Object invokeTester1 = classType.getConstructor(new Class[]{String.class}).newInstance(new Object[]{new String("測試一個帶參數的構造調用")});
        //獲取方法方式相同
        Method getStrMethod = classType.getMethod("getStr");
        Object str = getStrMethod.invoke(invokeTester1);
        System.out.println(str);
    }
}

 

 
在例程InvokeTester類的main()方法中,運用反射機制調用一個InvokeTester對象的add()和echo()方法
 
add()方法的兩個參數爲int 類型,得到表示add()方法的Method對象的代碼以下:
Method addMethod=classType.getMethod("add",new Class[]{int.class,int.class});
Method類的invoke(Object obj,Object args[])方法接收的參數必須爲對象,若是參數爲基本類型數據,必須轉換爲相應的包裝類型的對象。invoke()方法的返回值老是對象,若是實際被調用的方法的返回類型是基本類型數據,那麼invoke()方法會把它轉換爲相應的包裝類型的對象,再將其返回。
 
在本例中,儘管InvokeTester 類的add()方法的兩個參數以及返回值都是int類型,調用add Method 對象的invoke()方法時,只能傳遞Integer 類型的參數,而且invoke()方法的返回類型也是Integer 類型,Integer 類是int 基本類型的包裝類:
 
Object result=addMethod.invoke(invokeTester,
new Object[]{new Integer(100),new Integer(200)});
System.out.println((Integer)result); //result 爲Integer類型
 
 
博客搬家了。本文新地址: http://www.zicheng.net/article/3
相關文章
相關標籤/搜索