How can we obtain the name of the current method in Java?

In Java, it is possible to retrieve the method name of the current method using reflection. Here is an example code:

import java.lang.reflect.Method;

public class Main {
    public static void main(String[] args) {
        try {
            Method method = Main.class.getDeclaredMethod("getCurrentMethodName");
            System.out.println("当前方法名为: " + method.getName());
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        }
    }

    public static void getCurrentMethodName() {
        // 获取当前方法名
        System.out.println("调用方法:" + new Object(){}.getClass().getEnclosingMethod().getName());
    }
}

In the example above, you can retrieve the current method’s name by calling the getCurrentMethodName method. Another way to get the current method’s name is by using new Object(){}.getClass().getEnclosingMethod().getName().

Leave a Reply 0

Your email address will not be published. Required fields are marked *


广告
Closing in 10 seconds
bannerAds