Created
March 23, 2017 23:07
-
-
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()
This file contains hidden or 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("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