Java:获取当前执行的函数名


#Java 笔记


方式1: 使用函数内部类/匿名类对象的 getEnclosingMethod 方法

public class MethodNameTest {

	public static void testMethod() {
		String methodName = new Object() {}
				.getClass()
				.getEnclosingMethod()
				.getName();
		System.out.println(methodName);
	}

	public static void main(String[] args) {
		testMethod();
	}

}

运行结果:

testMethod

方式2: 从异常堆栈跟踪中获取方法名

public class MethodNameTest {

	public static void testMethod() {
		StackTraceElement[] stackTrace = new Throwable().getStackTrace();
		String methodName = stackTrace[0].getMethodName();
		System.out.println(methodName);
	}

	public static void main(String[] args) {
		testMethod();
	}

}

运行结果:

testMethod

方式3: 从线程堆栈跟踪中获取方法名

public class MethodNameTest {

	public static void testMethod() {
		StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
		String methodName = stackTrace[1].getMethodName();
		System.out.println(methodName);
	}

	public static void main(String[] args) {
		testMethod();
	}

}

运行结果:

testMethod

参考



( 本文完 )