Over a million developers have joined DZone.

Reflection - Find The Caller

DZone's Guide to

Reflection - Find The Caller

Free Resource
We can use reflection to find the caller of a method from  within the method. 

This class uses reflection to fetch the caller of the method. Note that this works only with Sun's JDK implementation.

public class CallerID {
	public static Class
   whoAmI() {
		return sun.reflect.Reflection.getCallerClass(2);

Here is the class for main method:

public class CallerIDTest {
	public static void main(String[] args) {

Program Output:
class com.test.reflection.CallerIDTest

Reference: http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

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


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

{{ parent.tldr }}

{{ parent.urlSource.name }}