{
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();
}
}