Skip to content

Instantly share code, notes, and snippets.

@khsthomas
Forked from artem-smotrakov/App.java
Created April 21, 2025 08:05
Show Gist options
  • Select an option

  • Save khsthomas/b46ba795b4567fca8f3144980b531221 to your computer and use it in GitHub Desktop.

Select an option

Save khsthomas/b46ba795b4567fca8f3144980b531221 to your computer and use it in GitHub Desktop.
Getting a caller's class name in Java with Thread.currentThread().getStackTrace()
public class App {
public static void main(String[] args) throws Throwable {
Logger.INSTANCE.log("started");
Logger.INSTANCE.log("hello");
foo();
Logger.INSTANCE.log("finished");
}
private static void foo() {
Logger.INSTANCE.log("hello from foo");
}
private static class Logger extends SecurityManager {
public static final Logger INSTANCE = new Logger();
public void log(String message) {
StackTraceElement ste = Thread.currentThread().getStackTrace()[2];
String callerClass = ste.getClassName();
String callerMethod = ste.getMethodName();
System.out.printf("[%s, %s]: %s%n", callerClass, callerMethod, message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment