How do I get the name of current executed method?

package org.kodejava.example.lang;

public class GetCurrentMethodName {
    public static void main(String[] args) {
        // Get the current executing method name
        String methodName =
            Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("methodName = " + methodName);

        GetCurrentMethodName obj = new GetCurrentMethodName();
        obj.executeAMethod();
    }

    private void executeAMethod() {
        // Get the current executing method name
        String methodName =
            Thread.currentThread().getStackTrace()[1].getMethodName();
        System.out.println("methodName = " + methodName);
    }
}

This program will print out the following string:

methodName = main
methodName = executeAMethod

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you šŸ™‚.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.