一.概述
在前面已經介紹了關於Java.lang.reflect.*包中的一些基本的知識。這裡通過對上文提供的一個執行個體進行實際編程並測試。
這裡分別使用了兩個包中的兩個類。所用到的包及包中的檔案清單如下:
testclass包:該包中包含一個編譯過的類class1,該類只有一個方法add。
dyn_callmethod包:該包中包含一個已編譯的類callclass,該類包含做為主調函數的主函數main()。該函數將實現動態調用testclass包中的class1類的add函數。
二.原始碼
1.testclass包的class1類:
package testclass;
public class class1 {
public class1() {
}
public int add(int a,int b){
return a+b;
}
}
2.dyn_callmethod包中的callclass類:
package dyn_callmethod;
import java.lang.reflect.*;
import testclass.*;
public class callclass {
public callclass() {
}
public static void main(String args[]){
try{
Class cls = Class.forName("testclass.class1");
System.out.println("Load the target class");
Class partypes[] = new Class[2];
partypes[0] = Integer.TYPE;
partypes[1] = Integer.TYPE;
Method meth = cls.getMethod("add", partypes);
System.out.println("get the method of the class");
testclass.class1 methobj = new testclass.class1();
Object arglist[] = new Object[2];
arglist[0] = new Integer(37);
arglist[1] = new Integer(47);
Object retobj = meth.invoke(methobj, arglist);
Integer retval = (Integer)retobj;
System.out.println(retval.intValue());
}
catch(Exception e){
System.err.println(e);
}
}
}
3.運行後輸出結果:
Load the target class
get the method of the class
84