在学动态代理的时候有没有看到这个Method类?有没有看见invoke方法?
哈哈,所以来回顾一下Method的用法吧!
package testJavaSE;
import java.lang.reflect.Method;
public class testMethodPerson {
public static void main(String[] args) throws Exception {
//获得Person的Class对象
Class<?> cls = testJavaSE.Person.class;//Class.forName("testJavaSE.Person");
//创建Person实例
Person p = (Person)cls.newInstance();
//获得Person的Method对象,参数为方法名,参数列表的类型Class对象
Method method = cls.getMethod("eat",String.class);
//invoke方法,参数为Person实例对象,和想要调用的方法参数
String value = (String)method.invoke(p,"肉");
//输出invoke方法的返回值
System.out.println(value);
//控制台输出:
//吃肉
//返回值
}
}
class Person{
public String eat(String food) {
System.out.println("吃"+food);
return "返回值";
}
}
具体解释注释都有,就不再多说。