简体   繁体   中英

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 CI 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?

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);

As something asynchroneous is involved, split the call up, and let the API return the ID.

Ticket callTicket = api.call(params);
Logger.getLogger(getClass().getName(), Level.FINE, callTicket);
Result result = callTicket.get();

Above having a result returned (synchroneously) is probably not the case with your code. Your code will get the result delived elsewhere. But that could be a ticket system too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM