Skip to content

Instantly share code, notes, and snippets.

@artem-smotrakov
Created March 23, 2017 23:07
Show Gist options
  • Select an option

  • Save artem-smotrakov/622ac7d5b53bbfc297cd5749f5b43bf6 to your computer and use it in GitHub Desktop.

Select an option

Save artem-smotrakov/622ac7d5b53bbfc297cd5749f5b43bf6 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