java.lang.reflect.Method.invoke(Object obj, Object... args)
方法使用指定的引數呼叫由此Method
物件表示的底層方法,個別引數自動展開以匹配原始形式引數,原始參考引數和參考引數都需要進行方法呼叫轉換。
以下是java.lang.reflect.Method.invoke(Object obj, Object... args)
方法的宣告。
public Object invoke(Object obj, Object... args)
throws IllegalAccessException, IllegalArgumentException,
InvocationTargetException
引數
返回值
args
將由物件表示的方法排程obj
上的結果。異常
以下範例顯示java.lang.reflect.Method.invoke(Object obj, Object...args)
方法的用法。
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class MethodDemo {
public static void main(String[] args)
throws IllegalAccessException, IllegalArgumentException, InvocationTargetException {
Method[] methods = SampleClass.class.getMethods();
SampleClass sampleObject = new SampleClass();
methods[1].invoke(sampleObject, "data");
System.out.println(methods[0].invoke(sampleObject));
}
}
class SampleClass {
private String sampleField;
public String getSampleField() {
return sampleField;
}
public void setSampleField(String sampleField) {
this.sampleField = sampleField;
}
}
讓我們編譯並執行上面的程式,這將產生以下結果 -
data