Getting the class name from a static method in Java
Using Thread.currentThread().getStackTrace() provides a workaround to retrieve the class name from within a static method:
The magic index 2 corresponds to your static method's caller in the call stack. Keep in mind, the exact index may vary based on context.
Methods across Java versions
Java 7 and later: MethodHandles.lookup()
Java 7 introduced an elegant way to get class names in a static context:
Pre-Java 7: new Object() trick
Are you dealing with code fossils - application still running on versions before Java 7? The following workaround has your back:
This involves creating an anonymous inner class that holds a reference to its enclosing class.
Expert's caution
Avoid heavy use of Thread.currentThread().getStackTrace(), as it might cause performance issues. Devs sticking with proven practices prefer MethodHandles.lookup().lookupClass().
Upgrade your error handling and logging
Class names pimp your error messages and exceptions for better understanding. They can also power up a shared logger or an error handling unit:
SecurityManager: A peep-hole to the call stack
If thrill excites you, how about using SecurityManager to sneak a peek into the call stack?
Remember, it depends on the active SecurityManager, a service that might be missing in some secure environments.
Sauntering in Kotlin's woods
Kotlin also employs a similar approach with a garnish of logging factories. A Java dev peeking into Kotlin land might find this intriguing:
Was this article helpful?