package org.nhooo.example.lang; public class GetCurrentMethodName { public static void main(String[] args) { // 获取当前执行方法的名称 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("methodName = " + methodName); GetCurrentMethodName obj = new GetCurrentMethodName(); obj.executeAMethod(); } private void executeAMethod() { // 获取当前执行方法的名称 String methodName = Thread.currentThread().getStackTrace()[1].getMethodName(); System.out.println("methodName = " + methodName); } }
该程序将打印以下字符串:
methodName = main methodName = executeAMethod