例如:程序执行时调用了com.weberyb.bbs.action这个包中的UserAction这个类中的getList这个方法,请问有什么办法拿到这个方法的名字吗?
[b]问题补充:[/b]
用反射的话只能拿指定的方法名,不过我想要的是方法名是action执行时从struts.xml的配置文件中动态解析出来的方法名;
例如:userAction 中有很多方法,在action执行时struts根据
解析出要用的方法是reg这个方法,那如果用Class c= Class.forname(classname)得到的只是userAction这个类,并不知道需要调用的具体的方法名,我想做成一个通用的类,当action执行的时候就动态的知道调用的是哪个类中的哪个方法,那请问要如何实现呢?难道要去动态解析xml文件吗?那用反射去获得类好像就没有什么意义了 8)
[b]问题补充:[/b]
请问lovewhzlq那还有什么办法去实现动态拿方法名这个做法吗?
[b]问题补充:[/b]
whistler兄弟可能误解我的意思了,我的项目是用ssh做的,用的struts2做的mvc,不是struts。不过你说所说的的确是解决问题的办法,不过我的项目写的都很多了,要来改成这样的写法太麻烦,刚刚想了下,于是直接用
ServletActionContext.getRequest().getServletPath()这个方法得到了action请求的url,在用正则表达式匹配出×××.action来解决了这个问题
利用反射
struts1.x的配置文件中action元素并没有method这个参数,方法的确定是根据中parameter这个参数的值method来确定。
当你想要请求UserAction的addUser方法时,应该提供名称为method的这么一个参数,其值为addUser,即 http://主机名:端口号/UserAction?method=addUser
大概的[color=red]模拟[/color]实现时这样的:
目标UserAction继承org.apache.struts.actions.DispatchAction,DispatchAction继承org.apache.struts.action。
/**
这个类用来处理Dispatch(分发)的实现
/
public class DispatchAction implements Action{
protected Class clazz = this.getClass();
protected Class[] types =
{
ActionMapping.class,
ActionForm.class,
HttpServletRequest.class,
HttpServletResponse.class
};
/*
/**
@return ActionForward
*/
public ActionForward dispachMethod(
ActionMapping mapping,
ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
ActionForward forward = null;
[color=green]/*通过调用ActionMapping 的实例mapping的getParameter()我们可以获得parameter这个参数的值即method*/[/color]
String parameterNmae = mapping.getParameter();
[color=green]/*根据“method”获得目标方法名称“addUser”*/[/color]
String methodName = request.getParameter(parameterNmae);
try
{
[color=green]/*利用反射根据方法名称“addUser”和参数类型数组types获得目标方法的实例*/[/color]
Method method = clazz.getMethod(methodName, types);
[color=green]/*构造参数实例数组*/[/color]
Object[] typesVlaues = new Object[]{request,response,mapping,form};
[color=green]/*执行目标对象的目标方法*/[/color]
forward = (ActionForward)method.invoke(this, parameterVlaues);
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return forward;
}
java反射机制
这是用反射的机制实现了
Method[] methods = com.weberyb.bbs.action.UserAction.class.getDeclaredMethods();
//得到UserAction类的所有方法
Method getlist = com.weberyb.bbs.action.UserAction.class.getDeclaredMethod("getList",Class... parameterTypes/* 方法参数类型*/)
你要这样的话,那你就去动态解析xml文件嘛,