Created
March 23, 2017 22:51
-
-
Save artem-smotrakov/d0fc3c4c26858051ca8901dd017306b8 to your computer and use it in GitHub Desktop.
Getting a caller's class name in Java with SecurityManager.getClassContext()
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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