How to get the parameters of a method using reflection
I'm stuck on this issue. I'm fairly new 开发者_Go百科to reflection.
I have a method, say:
void foo(String s, int i){...}
Say someone calls this method with inputs of foo("hey", 5);
How can I get the values "hey" and 5 using reflection? When I try to do it I just get a whole bunch of the String and Integer object variables.
It sounds like you are talking about AOP(aspect oriented programming) - not reflection. A method interceptor would give you access to the invocation at runtime (including access to the arguments). How you access the arguments depends on the 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;
}
}
Note: AOP is an advanced technology and you would need to do some homework to use it effectively. See http://static.springsource.org/spring/docs/2.0.2/reference/aop-api.html for details on the example given above.
Reflection is about accessing the program at a "meta" level, so you can tinker with the details (objects, classes) of how it is put together. Accessing the actual values of variables and parameters is done at the usual "normal" level.
I'm not sure why you cannot access the parameters at the usual "normal, non-meta" level, maybe you are trying to see the parameters to a method up in the stack, or on another thread? For that, you'll probably need using a debugging interface like JDI.
I think reflection is a misguided way to think about achieving what you want to do here.
Think of reflection as looking at a car and finding out that it has wheels, engine, seats etc and what type they are. Its not about finding out how these parts are working at a given moment. I know its not a very good analogy but I hope it helps. Reflection means you are looking at the car from outside and deciding what it looks like and what it can do. Finding out the values of the arguments is done from the "inside".
Basically if you have a java class, you can use reflection to know what methods, attributes it has and what are their types and invoke them too. But what you are looking to do here with reflection is like calling a method and magically finding out its arguments from "outside" the method.
You said "I am practicing, and I want to output everything to a display". why don't you just log the arguments or print them to an output stream? Or as someone said, use a debugger.
精彩评论