Home > Software engineering >  How to get the method's parameter expression stack or string representation?
How to get the method's parameter expression stack or string representation?

Time:01-13

I am writing a method for debugging and metrics capturing, such that:

void capture(Object value, String debugName) {
  System.out.println("captured "   debugName   " with value "   value);
}

and calling it with:

capture(foo.bar(), "foo.bar");

Is there any way to get the value expression string directly, so I don't need to pass the debugName? Something like:

void capture(Object value) {
  System.out.println("captured "   getStack(value)   " with value "   value);
}

CodePudding user response:

You can log where capture was called:

public class Test {
    public static void capture(Object value) {
        Exception e = new Exception();
        System.out.println("captured value "   value   " at "   e.getStackTrace()[1]);
    }

    public static void someFunc() {
        capture("alice");
    }

    public static void main(String[] args) {
        capture("fred");
        someFunc();
    }
}

which prints:

captured value fred at Test.main(Test.java:25)
captured value alice at Test.someFunc(Test.java:21)

CodePudding user response:

The only way you could use the stack to figure out something about the foo.bar() call is to run that capture() code from within the bar() method itself, i.e. some AOP framework or some java.lang.reflect.Proxy-based approach to inject your code into bar() itself.

The stack of capture() in your example can never hint at foo.bar(), but to whatever method called capture. If you make foo.bar() invoke it, you can get the TypeOfFoo.bar() information from Thread.currentThread().getStackTrace()[1].

However, there's no way to figure out the name foo (in your example), so you would have to live with captured TypeOfFoo.bar() with value ...

  • Related