as follows:
public Object invokeMethod(String className, String methodName,Object[] args) throws Exception{Class ownerClass = Class.forName(className);Object owner = ownerClass.newInstance(); 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);}However, in our actual application, we will also encounter a situation where the incoming actual parameters and the formal parameters of the method to be called may not be completely consistent:
For example, when a method in struts1.x is called, it will have parameters of type HttpServletResponse.
In tomcat, the instance of the request object is actually: org.apache.catalina.connector.ResponseFacade
It implements the interface: javax.servlet.http.HttpServletResponse;
If we directly treat the request object in the web container as a parameter and pass it into the above code snippet, there will be a problem. At this time, our handling method is like this. In action, the method is generally like:
public ActionForward query(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
The response is generally located in the fourth one, so let’s modify the above code:
Bundle
for (int i = 0, j = args.length; i < j; i++) { argsClass[i] = args[i].getClass(); }Change to:
for (int i = 0, j = args.length; i < j; i++) { if(i == 3){ argsClass[i] = HttpServletResponse.class; } else{ argsClass[i] = args[i].getClass(); } }The above summary (recommended) of dynamically calling a certain method through the Java reflection mechanism is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.