Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine where method was called

I provide an API and need to know, where methods of the API were invoked. I could of cause use reflection or the thread stacktrace, but that would include a lot of runtime cost.

I do not need the exact class name, a unique reference per invocation would be sufficient. In C I would normally use the preprocessor to automatically add __FILE__ and __LINE__ to the method invocation.

Is there a method in Java (besides code generation) to get a unique caller identification with low runtime cost?

like image 420
ooxi Avatar asked Sep 29 '16 08:09

ooxi


1 Answers

One solution would be to have a cached Throwable which is passed in.

class StackPoint {
    Throwable stack;
    public Throwable getStack() {
        if (stack == null)
            stack = new Throwable();
        return stack;
    }
}

public void methodToCall(StackPoint sp) {
    Throwable t = sp.getStack();

}


static final StackPoint one = new StackPoint();

methodToCall(one); // Have to remember to give each line a different StackPoint.

Note: if the method which calls this caller changes, you only record the first one ever.


There isn't a standard pattern and it is likely that if you want this to be efficient the caller will need to pass a unique id. The closest you can do is use is a lambda.

public void methodToCall(Runnable run) {
    Class id = run.getClass();

}

You can call it like this

methodtoCall(()->{});

This will create a different class for each place it is called, even if it appears multiple times on the same line. It creates no garbage as it reuses the same object each time. You could make this shorter with

void methodToCall(IntFunction fun) {

}

and call

methodToCall(a->1);
like image 113
Peter Lawrey Avatar answered Sep 28 '22 16:09

Peter Lawrey