Find out method argument values at run time
Hi,
I am looking to find out the argument names and values of a method at run time. (This would allow for instance to automatically log argument names and values without writing tedious code).
The following thread did not seem to answer this problem
http://forum.java.sun.com/thread.jspa?forumID=4&threadID=411455
Any suggestions welcomed
Ben
[383 byte] By [
BenDavea] at [2007-10-3 4:54:00]

As there is no Method-Object representing the current method call, I doubt you will get hands on the arguments passed to the method other than referencing them or building a framework "on top" (as, e.g., AspectJ). Also, Method in reflections does not hold the names of parameters, so it will be difficult to automatically print information on more than the signature.
The following is a not very robust, little play-around code for logging. Maybe it delivers enough information for some situations:
public class Test {
void test(String arg0, int arg1) {
log(new MethodGetter(){}.get(), arg0, arg1);
}
public static void main(String[] args) {
new Test().test("zero", 1);
}
public static final void log(Method method, Object ... args) {
final StringBuilder builder = new StringBuilder();
builder.append(method.getDeclaringClass().getSimpleName()).append('.');
builder.append(method.getName()).append('(');
final Class<?>[] parameterTypes = method.getParameterTypes();
for (int index = 0; index < parameterTypes.length; index++) {
if (index > 0) {
builder.append(", ");
}
builder.append('(').append(parameterTypes[index].getSimpleName()).append(") ");
if (index < args.length) {
builder.append(args[index]);
} else {
builder.append("null");
}
}
builder.append(");");
System.out.println(builder.toString());
}
public static abstract class MethodGetter {
public Method get() {
return getClass().getEnclosingMethod();
}
}
}
It will print the following:
Test.test((String) zero, (int) 1);
Note that MethodGetter and log and main are enclosed for test purpose only.