Getting the name of the currently executing method

前端 未结 22 2593
闹比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:37

    I've got solution using this (In Android)

    /**
     * @param className       fully qualified className
     *                        
    * YourClassName.class.getName(); *

    * @param classSimpleName simpleClassName *
    * YourClassName.class.getSimpleName(); *

    */ 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())})); } }

提交回复
热议问题