Over a million developers have joined DZone.

Runtime Class and Method information

· Java Zone

Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code! Brought to you in partnership with ZeroTurnaround.

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();
System.out.println(elements[0].getMethodName());

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.

Thread.currentThread().getStackTrace()[1].getClassName()


Tiny little things, aren't they!

Happy Programming :)
Signing Off

From http://mycodefixes.blogspot.com/2011/03/runtime-class-and-method-information.html

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

Topics:

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}