Skip to main content

ProwessApps

Learn · Practice · Excel

Java Program to print the name of current-method and class.

Java Code Example — Utility Programs

ADVERTISEMENT

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

  1. Get the current executing thread using Thread.currentThread().
  2. Retrieve the execution stack trace array using t.getStackTrace().
  3. Access index 1 of the array (index 0 is the getStackTrace call itself).
  4. Use info.getMethodName() and info.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)
ADVERTISEMENT