1

I'm trying to get some runtime information to do some debugging. Is there a way to access the parameters actually passed to a method?

I know the calling class and method, but not the parameters and their value at runtime. Any Ideas how to solve this? Thanks in advance.

My code so far:

//get the class I wanna know something about out of the call history
StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
String callerMethod = stacktrace[2].getMethodName();

//load the class to get the information
Class<?> c = Class.forName(stacktrace[2].getClassName());
Method[] methods = c.getMethods();
Class<?>[] parameters = methods[1].getParameterTypes();

//get the parameter data
(parameters[y].isArray()? parameters[y].getComponentType() : parameters[y]).getName();

//TODO: how about the parameter value at runtime?

The code has to be generic for all Classes I will implement. Example of usage:

public class doClass() {
  public void doSomething(Object o) {
    //here comes my debug line
    magicDebugger(level);
  }
}

level is the switch/trigger to activate console/db/file/mail output or whatever of some information

I expect following output (maybe there's some System.out.println in the magicDebugger class):

[debug] caller: com.company.package.doClass.doSomething(Object o); value of o at runtime = java.lang.String "test"
Ben
  • 391
  • 5
  • 13
  • 2
    you can use aspects to handle it or you debug your code in ecllipse like editor – Girish Feb 05 '14 at 12:02
  • It has to be debuggable via console. I cannot use eclipse to do this. – Ben Feb 05 '14 at 12:16
  • Another dup: https://stackoverflow.com/questions/4943612/java-how-to-get-arguments-passed-to-method-that-called-this-method – Vadzim Jun 13 '19 at 17:47

2 Answers2

1

you can use http://docs.oracle.com/javase/6/docs/api/java/lang/reflect/Proxy.html Proxy class or AspectJ framework to do that

Girish
  • 1,717
  • 1
  • 18
  • 30
  • I tried to code a proxy and this pattern works fine. Though I still hestitate to change all lines of code I have ;) – Ben Feb 06 '14 at 16:09
0

Look into using reflection for this. That should provide what you're looking for.

Thom
  • 14,013
  • 25
  • 105
  • 185