Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Runtime Class and Method information

DZone's Guide to

Runtime Class and Method information

· Java Zone
Free Resource

Try Okta to add social login, MFA, and OpenID Connect support to your Java app in minutes. Create a free developer account today and never build auth again.

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

Build and launch faster with Okta’s user management API. Register today for the free forever developer edition!

Topics:

Opinions expressed by DZone contributors are their own.

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

{{ parent.tldr }}

{{ parent.urlSource.name }}