我被这个问题困扰了。我对反射(reflection)还很陌生。
我有一个方法,说:
void foo(String s, int i){...}
假设有人使用 foo("hey", 5); 的输入调用此方法;
如何使用反射获取值“hey”和 5?当我尝试这样做时,我只是得到一大堆 String 和 Integer 对象变量。
最佳答案
听起来你在谈论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;
}
}
注意:AOP 是一项先进技术,您需要做一些功课才能有效地使用它。请参阅http://static.springsource.org/spring/docs/2.0.2/reference/aop-api.html有关上面给出的示例的详细信息。
关于java - 如何使用反射获取方法的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5984296/