Skip to content

Instantly share code, notes, and snippets.

@artem-smotrakov
Created March 23, 2017 22:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save artem-smotrakov/d0fc3c4c26858051ca8901dd017306b8 to your computer and use it in GitHub Desktop.
Save artem-smotrakov/d0fc3c4c26858051ca8901dd017306b8 to your computer and use it in GitHub Desktop.
Getting a caller's class name in Java with SecurityManager.getClassContext()
public class App {
public static void main(String[] args) throws Throwable {
Logger.INSTANCE.log("main() started");
Logger.INSTANCE.log("hello");
Logger.INSTANCE.log("main() finished");
}
private static class Logger extends SecurityManager {
public static final Logger INSTANCE = new Logger();
public void log(String message) {
Class caller = getClassContext()[1];
System.out.printf("[%s]: %s%n", caller.getName(), message);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment