Java Stack Walking Java
Following example shows how to find the current method name by using Java 9 StackWalker.
package com.logicbig.example;public class StackWalkerCurrentMethodName { public static String getCurrentMethodName() { StackWalker stackWalker = StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE); StackWalker.StackFrame frame = stackWalker.walk(stream1 -> stream1.skip(1) .findFirst() .orElse(null)); return frame == null ? "caller: null" : frame.getMethodName(); } public static void main(String[] args) { testMethod(); } public static void testMethod() { String methodName = getCurrentMethodName(); System.out.println(methodName); }}
testMethod