java反射包Method類學(xué)習(xí)小例子 -=
method.invoke(調(diào)用該方法的對(duì)象,該方法需要傳入的參數(shù));
method代表被調(diào)用方法(方法的實(shí)例對(duì)象)
method.invoke()方法的返回值是Objec類型,所以具體用的時(shí)候可能需要強(qiáng)制轉(zhuǎn)換類型
================Person類===============================
package test;
public class Person{
public String sayHello(String name){
System.out.println(name + ", 你好!");
return "OK!";
}
}
=====================測(cè)試t類Tes=====================
package test;
import java.lang.reflect.Method;
public class Test{
public static void main(String[] args) throws Exception{
Class clazz = Class.forName("test.Person");
Person person = (Person)clazz.newInstance();
String methodName = "sayHello";
Method method = clazz.getMethod(methodName, String.class);
String returnValue = (String) method.invoke(person, "張三");
System.out.prinltn("returnValue: " + returnValue);
}
}
method.invoke方法也是動(dòng)態(tài)代理類中用到的一個(gè)基礎(chǔ)知識(shí),明白了這個(gè)在看InvokationHandler接口實(shí)現(xiàn)類的invoke方法會(huì)相對(duì)容易些。
更多建議: