Getting the name of the currently executing method

前端 未结 22 2207
闹比i
闹比i 2020-11-22 03:33

Is there a way to get the name of the currently executing method in Java?

相关标签:
22条回答
  • 2020-11-22 04:33
    MethodHandles.lookup().lookupClass().getEnclosingMethod().getName();
    
    0 讨论(0)
  • 2020-11-22 04:35

    Thread.currentThread().getStackTrace() will usually contain the method you’re calling it from but there are pitfalls (see Javadoc):

    Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this thread is permitted to return a zero-length array from this method.

    0 讨论(0)
  • 2020-11-22 04:37

    I've got solution using this (In Android)

    /**
     * @param className       fully qualified className
     *                        <br/>
     *                        <code>YourClassName.class.getName();</code>
     *                        <br/><br/>
     * @param classSimpleName simpleClassName
     *                        <br/>
     *                        <code>YourClassName.class.getSimpleName();</code>
     *                        <br/><br/>
     */
    public static void getStackTrace(final String className, final String classSimpleName) {
        final StackTraceElement[] steArray = Thread.currentThread().getStackTrace();
        int index = 0;
        for (StackTraceElement ste : steArray) {
            if (ste.getClassName().equals(className)) {
                break;
            }
            index++;
        }
        if (index >= steArray.length) {
            // Little Hacky
            Log.w(classSimpleName, Arrays.toString(new String[]{steArray[3].getMethodName(), String.valueOf(steArray[3].getLineNumber())}));
        } else {
            // Legitimate
            Log.w(classSimpleName, Arrays.toString(new String[]{steArray[index].getMethodName(), String.valueOf(steArray[index].getLineNumber())}));
        }
    }
    
    0 讨论(0)
  • 2020-11-22 04:38

    Both of these options work for me with Java:

    new Object(){}.getClass().getEnclosingMethod().getName()
    

    Or:

    Thread.currentThread().getStackTrace()[1].getMethodName()
    
    0 讨论(0)
提交回复
热议问题