先說明一下程序的功能,我寫了一個ReflectionClass,裏邊只有一個方法. 它的功能是返回傳入的String類型與Int類型相加之和. 在測試類Test中調用源類的方法.
1、ReflectionClass類,只有一個測試方法
public String test(String i1,int i2){
return i1+i2;
}
}
2、Test類
import java.lang.reflect.Method;
public class Test {
* @param args
* @throws ClassNotFoundException
* @throws ClassNotFoundException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws NoSuchFieldException
* @throws SecurityException
* @throws NoSuchMethodException
* @throws InvocationTargetException
* @throws IllegalArgumentException
*/
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SecurityException, NoSuchFieldException, NoSuchMethodException, IllegalArgumentException, InvocationTargetException{
// TODO Auto-generated method stub
Class Obj = null;
//返回指定位置的Class對象
Obj = Class.forName("com.ReflectionClass");
//存儲傳入參數的個數及類型
Class[] types = new Class[2];
types[0]=String.class;
types[1]=Integer.TYPE;
//傳入參數Value
Object[] objs = new Object[2];
//String類型,值是隨便寫的
objs[0] = new String("哈哈哈哈");
//int類型
objs[1] = new Integer(123);
//得到代表指定源類方法的對象,這裏第一個參數爲源類的方法名,第二個參數爲傳入的參數類型
Method method = Obj.getDeclaredMethod("test",types);
// 對帶有指定參數的指定對象調用由此 Method 對象表示的底層方法。
//簡單說就是執行指定的這個方法,打印出結果.這裏第一個參數爲從中調用底層方法的對象,第二個參數爲傳入的數據Value
String result = method.invoke(Obj, objs).toString();
//輸出結果,這裏輸出爲:哈哈哈哈123
System.out.println("這個是調用源類的方法的結果"+result);
}
}