如何使用反射获取方法的参数

use*_*949 2 java reflection

我坚持这个问题.我很反思.

我有一个方法,说:

void foo(String s, int i){...}
Run Code Online (Sandbox Code Playgroud)

假设有人用输入调用此方法 foo("hey", 5);

如何使用反射获得值"嘿"和5?当我尝试这样做时,我只获得了一大堆String和Integer对象变量.

les*_*es2 8

听起来你在谈论AOP(面向方面​​编程) - 而不是反思.方法拦截器将允许您在运行时访问调用(包括访问参数).如何访问参数取决于API.

public class MyMethodInterceptor implements MethodInterceptor {

    public Object invoke(MethodInvocation invocation) throws Throwable {
        System.out.println("Before: invocation=[" + invocation + "]");

        // use MethodInvocation.getArguments() to access the runtime parameters
        System.out.println(Arrays.toString(methodInvocation.getArguments()));

        Object rval = invocation.proceed();
        System.out.println("Invocation returned");
        return rval;
    }
}
Run Code Online (Sandbox Code Playgroud)

注意:AOP是一项先进技术,您需要做一些功课才能有效地使用它.有关上面给出的示例的详细信息,请参见http://static.springsource.org/spring/docs/2.0.2/reference/aop-api.html.