user3389 2011-03-07 13:55
浏览 199
已采纳

如何用反射(或其他方法)得到方法参数的名称

如何用反射(或其他方法)得到方法参数的名称
请看如下代码(需求)

package com.servlet;
public class Controller
{
public String login(String username,String userpwd)
{
return null;
}
}

public class LoginServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException
{
Controller targetObj = new Controller();
Class<Controller> clazz = Controller.class;
Method[] methods = clazz.getMethods();
for(Method method : methods)
{
if("login".equals(method.getName()))
{
try
{
Class[] classs = method.getParameterTypes();
Object[] params = new Object[classs.length];
for(int i=0;i<classs.length;i++)
{
Class tempClazz = classs[i];
//[color=red]请问此处该如何得到login方法的参数字符串的名称(username,userpwd)[/color] //[color=red]我得到这两个字符串之后,直接用[/color]request.getParameter(username),request.getParameter(userpwd)
Array.set(params, i, request.getParameter("username"));
}
String result = method.invoke(targetObj, params).toString();
//do Other Thing
}catch(Exception e)
{
e.printStackTrace();
}
}
}
}
}



得到方法参数的个数,类型很容易。只是得到那个名称(起的名字)不是很容易

我想了很久,也没想出来该怎么做(springmvc里面有类似的功能,但是spring源代码太杂了,没找到)

???
问题补充
我就是想自己写,不依赖其他任何技术或框架。。。。

求思路或代码
  • 写回答

6条回答 默认 最新

  • gosudream 2011-03-07 13:55
    关注

    用注解应该能解决这问题把
    以前用mybatis的时候,它好像就是这么处理map参数名的

    [code="java"]
    import java.lang.annotation.ElementType;
    import java.lang.annotation.Retention;
    import java.lang.annotation.RetentionPolicy;
    import java.lang.annotation.Target;

    @Retention(RetentionPolicy.RUNTIME)
    @Target(ElementType.PARAMETER)
    public @interface Param {
    String value();
    }
    [/code]

    [code="java"]
    import java.lang.reflect.Method;

    public class ParameterAnnotation {
    public static void main(String[] args) throws Exception {
    Method method = ParameterAnnotation.class.getMethod(
    "doSomething", Integer.class, String.class);
    for (int i = 0; i < method.getParameterTypes().length; i++) {
    Param param = (Param)method.getParameterAnnotations()[i][0];
    System.out.printf("Parameter name #%d: %s\n", i, param.value());
    }
    }

    public void doSomething(@Param("arg1")Integer arg1, @Param("arg2")String arg2) {
    
    }
    

    }
    [/code]

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?