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
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
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
( 本文完 )