Search code examples
javamethodsjava-threads

Is there a better way than parsing a stack trace to get the currently running or calling method?


The historical method has been to parse the output of Thread.currentThread().getStackTrace(), but there have been so many changes since Java 8 (like method handles) that I wasn't sure if a better way now exists.

If it helps, my specific goal here is to act based on annotations on the calling method, if possible.


Solution

  • Java 9 introduced the StackWalker API

    It's best practice to store your StackWalker instance in a private static final field:

    class SomeClass {
        private static final StackWalker SW = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
    
        public someCallerSensitiveMethod() {
            Class<?> caller = SW.getCallerClass();
            // Do something with it, like check it's annotations
        }
    }