Getting the name of the currently executing method

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

    I rewritten a little the maklemenz's answer:

    private static Method m;
    
    static {
        try {
            m = Throwable.class.getDeclaredMethod(
                "getStackTraceElement",
                int.class
            );
        }
        catch (final NoSuchMethodException e) {
            throw new NoSuchMethodUncheckedException(e);
        }
        catch (final SecurityException e) {
            throw new SecurityUncheckedException(e);
        }
    }
    
    
    public static String getMethodName(int depth) {
        StackTraceElement element;
    
        final boolean accessible = m.isAccessible();
        m.setAccessible(true);
    
        try {
            element = (StackTraceElement) m.invoke(new Throwable(), 1 + depth);
        }
        catch (final IllegalAccessException e) {
            throw new IllegalAccessUncheckedException(e);
        }
        catch (final InvocationTargetException e) {
            throw new InvocationTargetUncheckedException(e);
        }
        finally {
            m.setAccessible(accessible);
        }
    
        return element.getMethodName();
    }
    
    public static String getMethodName() {
        return getMethodName(1);
    }
    
    

提交回复
热议问题