Java: How to get the caller function name

前端 未结 6 1162
情深已故
情深已故 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:45

    I have no idea why but in my shop the develop system differs from the test and production environments shifting position in the stack. I was forced to loop through the stack to find and get the calling method from the next element in the stack trace. A little clunkier but so far has been consistently returning the desired method. I use this as part of my error handling to identify where an exception was caught.

        List list = new ArrayList();
        StackTraceElement[] elements = Thread.currentThread().getStackTrace();
        for (int i = 0; i < Thread.currentThread().getStackTrace().length; i++) {
            System.out.println("Stack: "
                    + i
                    + " Class: "
                    + elements[i].getClassName()
                    + " Method: "
                    + elements[i].getMethodName());
            if (elements[i].getMethodName().equals("")) {
                list.add(elements[i + 1].getClassName());
                list.add(elements[i + 1].getMethodName());
                 break;
            } // if
        } // for
    

提交回复
热议问题