{
String className = mv.getClassName();
String methodName = mv.getMethodName();
//load class
Class controllerClass = cache.loadClass(className);//== Class.forName(className);java反射机制,jvm加载lassName类
Class parentControllerClass = cache.loadClass(baseControllerClass);//class org.bluechant.mvc.controller.Controller
//load method参数1类,创建一个方法为setRequest参数为HttpServletRequest.class的方法与method = clazz.getDeclaredMethod(setRequest, HttpServletRequest.class);与HttpServletRequest的setRequest方法一致的方法.
Method setRequest = cache.loadMethod(parentControllerClass, "setRequest", new Class[] { HttpServletRequest.class }); //HttpServletRequest.class,java的反射机制得到自己的类,能够拥有自己的方法值,(Method setRequest获取成员函数)
Method setModelAndView = cache.loadMethod(parentControllerClass, "setModelAndView", new Class[] { ModelAndView.class });//org.bluechant.mvc.controller.Controller-setModelAndView@6024418 public void org.bluechant.mvc.controller.Controller.setModelAndView(org.bluechant.mvc.controller.ModelAndView)
Method targetMethod = cache.loadMethod(controllerClass, methodName, new Class[]{});
//buiid controller instance and invoke target method以上setRequest,setModelAndView,targetMethod都放在cache(hashMap中)
Object instance = controllerClass.newInstance();//加载className类
setRequest.invoke(instance, new Object[] { request });//对带有指定参数的指定对象调用由此 Method 对象表示的基础方法
setModelAndView.invoke(instance, new Object[] { mv });//instance立即为原型指针
targetMethod.invoke(instance, new Object[]{});
//调用instance类中targetMethod这个方法,Object[]{}这个作为参数..
//invoke根据实体获得方法,添加所要造的参数,就是个找实例的方法克隆工厂,由Method获得实例模型,由方法锻造样子,传入参数得出想要结果
}
方法说明实例:
}
class ClassB{
public ClassB(){
System.out.println("this is ClassB");
}
public Object invokeMehton(Object owner,String methodName,Object[] args) throws Exception{
//根据methodName获得owner里面的方法。args是对应方案参数。
Class wnerClass=owner.getClass();
Class[] argsClass=new Class[args.length];
for(int i=0,j=args.length;i<j;i++){
argsClass[i] = args[i].getClass();
}
Method method = ownerClass.getMethod(methodName, argsClass);
return method.invoke(owner, args);
}
}
输出为
this is ClassB
300
outabccc
说明c调用Class方法成功。
import java.lang.reflect.Method;
public class ClassA {
//ClassA里面有add、和StringAdd两个不同方法。c是ClassB的Object
ClassB c=new ClassB();
public void add(Integer param1, Integer param2) {
System.out.println(param1 + param2);
}
public void StringAdd(String abc){
System.out.println("out"+abc);
}
public static void main(String[] args){
ClassA a=new ClassA();
try {
a.c.invokeMehton(a, "add",new Object[] {new Integer(100),new Integer(200)});//反射调用方法add
a.c.invokeMehton(a, "StringAdd",new Object[] {new String("abccc")});//反射调用方法StringAdd
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}