Java: how to get arguments passed to method that called this method?

Tom picture Tom · Feb 9, 2011 · Viewed 9k times · Source

In java, it is possible to get the class and method that called the current method (the method in which you get the StackTrace).

My question is, can I get the arguments that were passed to the method that called this method?

I need this for debugging purposes.

Eg:

baseClass {
   initialFunc(input) {
       var modifiedInput = input + " I modified you";
       otherClass.doSomething(modifiedInput);
   }
}

otherClass {
    doSomething(input)  {
         //GET THE ARGUMENTS PASSED TO THE METHOD OF THE CLASS THAT CALLED THIS METHOD
    }
}

Can one get this information from the stacktrace, or are there other means?

(Note that I need to be able to do this in runtime and cannot actually change the source of baseClass, this is going to be a feature of my debugging class that does not know the source beforehand)

Thanks.

Answer

aioobe picture aioobe · Feb 9, 2011

I don't believe this is possible using the standard Java API.

What you could do is to use AspectJ, place a point-cut at the calling method, save the arguments, place a point-cut at the called method and pass on the arguments.

Another option (slightly more advanced) is to use a custom, bytecode-rewriting, class loader that saves the original arguments, and passes them on as extra arguments to the next method. This would probably take a day or two to implement. Suitable frameworks are BCEL or ASM.