Java Program to print the name of current-method and class.
Objective
Write a Java program to dynamically print the name of the currently executing method and class.
Algorithm / Approach
- Get the current executing thread using
Thread.currentThread(). - Retrieve the execution stack trace array using
t.getStackTrace(). - Access index 1 of the array (index 0 is the
getStackTracecall itself). - Use
info.getMethodName()andinfo.getClassName()to print the details.
Test.java
class Test {
public static void main(String [] ar){
Thread t = Thread.currentThread();
StackTraceElement info;
info = t.getStackTrace()[1];
System.out.println(info.getMethodName());
System.out.println(info.getClassName());
show();
}
static void show(){
Thread t = Thread.currentThread();
StackTraceElement info;
info = t.getStackTrace()[1];
System.out.println(info.getMethodName());
System.out.println(info.getClassName());
}
}
Expected Output
main Test show Test
Explanation of the Program
- A Stack Trace is a snapshot of the call stack (the history of methods that have called each other to reach the current point in execution).
- This technique is incredibly useful for building advanced Logging frameworks, where you want to automatically log the exact class and method name that generated an error without having to hardcode the names manually.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)