Getting Name of Current Method inside a method in Java
- Java.lang.Class.getEnclosingMethod()- The java.lang.Class.getEnclosingMethod() returns a Method object representing the immediately enclosing method of the underlying class.
- StackTraceElement.getMethodName()-The java.lang.StackTraceElement.getMethodName() method returns the name of the method containing the execution point represented by this stack trace element.
- Thread.currentThread().getStackTrace()- Call Thread.currentThread().getStackTrace(). The second element, [1], is the your method call getStackTrace(); [0] is getStackTrace(). Then call its getMethodName() method to get the name of your method.
package com.javainuse;
public class TestGetMethodName {
public static void main(String args[]) {
getMethodNameUsingClassInstance();
getMethodNameUsingStackTraceElement();
getMethodNameUsingCurrentThread();
}
//Get method name using Java.lang.Class.getEnclosingMethod()
public static void getMethodNameUsingClassInstance() {
String methodNameUsingClassInstance =
new TestGetMethodName() {}.getClass().getEnclosingMethod().getName();
System.out.println("Current Method Execution Name Using Class Instance - " +
methodNameUsingClassInstance);
}
//Get method name using StackTraceElement.getMethodName()
public static void getMethodNameUsingStackTraceElement() {
StackTraceElement stackTraceElements[] = (new Throwable()).getStackTrace();
System.out.println("Current Method Execution Name Using StackTraceElement - " +
stackTraceElements[0].getMethodName());
}
//Get method name using Thread.currentThread().getStackTrace()
public static void getMethodNameUsingCurrentThread() {
System.out.println("Current Method Execution Name using Current Thread - " +
Thread.currentThread().getStackTrace()[1].getMethodName());
}
}
Download Source Code
Download it - Get Current Execution MethodSee Also
Understand Java 8 Method References using Simple Example Java - PermGen space vs MetaSpace Java 8 Lambda Expression- Hello World Example Java 8 Features Java Miscelleneous Topics Java Basic Topics Java- Main Menu
Popular Posts
1Z0-830 Java SE 21 Developer Certification
Azure AI Foundry Hello World
Azure AI Agent Hello World
Foundry vs Hub Projects
Build Agents with SDK
Bing Web Search Agent
Function Calling Agent
Spring Boot + Azure Key Vault Hello World Example
Spring Boot + Elasticsearch + Azure Key Vault Example
Spring Boot Azure AD (Entra ID) OAuth 2.0 Authentication
Deploy Spring Boot App to Azure App Service
Secure Azure App Service using Azure API Management
Deploy Spring Boot JAR to Azure App Service
Deploy Spring Boot + MySQL to Azure App Service
Spring Boot + Azure Managed Identity Example
Secure Spring Boot Azure Web App with Managed Identity + App Registration
Elasticsearch 8 Security - Integrate Azure AD OIDC