Java: How to get the caller function name

前端 未结 6 1160
情深已故
情深已故 2021-02-05 01:56

To fix a test case I need to identify whether the function is called from a particular caller function. I can\'t afford to add a boolean parameter because it would break the int

6条回答
  •  逝去的感伤
    2021-02-05 02:29

    I tweaked the code that is being discussed here and customized it to get the invoking method. What the code does here is to iterate over the stack trace elements and as soon as it finds the name of the method being invoked, it gets the name of the previous method, which in turn will be the method that is invoking this method.

        private String method() {
        String methodName=null;
        StackTraceElement[] stacktrace = Thread.currentThread().getStackTrace();
        for (int i = 0; i < stacktrace.length; i++) {
            if(stacktrace[i].getMethodName().equals("method")) {
                methodName = stacktrace[i+1].getMethodName();
                break;
            }
        }
          return methodName;
    
    }
    

提交回复
热议问题