Thursday, March 17, 2011

Runtime Class and Method information

Here is a small snippet that can be used to find the name of the currently executing method in Java.

Throwable t = new Throwable(); 
StackTraceElement[] elements = t.getStackTrace(); 

Create a Throwable object in your method. During the creation of a Throwable instance, the JVM stores information of the currently executing method on the stack trace. Extract the stack trace and print the name of the zeroth element to get your method name.

Here is another small snippet to find the name of the class at runtime.


Tiny little things, aren't they!

Happy Programming :)
Signing Off