Como obter o nome do método atual em Java?
Veja a seguir algumas formas de obter o nome do método corrente em Java.
Obtendo o nome do método corrente usando uma classe local
public class MyClass {
public void myMethod() {
class Local {};
String methodName = Local.class.getEnclosingMethod().getName();
System.out.println(methodName);
}
}
Obtendo o nome do método corrente usando StackTrace
public class MyClass {
public void myMethod() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(methodName);
}
}
Criando um método para obter o nome do método corrente
public class MyClass {
public static String getMethodName() {
return Thread.currentThread().getStackTrace()[2].getMethodName();
}
public void myMethod() {
System.out.println(getMethodName());
}
}
public class MyClass {
public void myMethod() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
System.out.println(methodName);
}
}