Platinum Partner

Reflection - Find The Caller

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) {
		System.out.println(CallerID.whoAmI());
	}
}


Program Output:
class com.test.reflection.CallerIDTest

Reference: http://www.javaspecialists.eu/talks/oslo09/ReflectionMadness.pdf
{{ tag }}, {{tag}},

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

{{ parent.tldr }}

{{ parent.urlSource.name }}
{{ parent.authors[0].realName || parent.author}}

{{ parent.authors[0].tagline || parent.tagline }}

{{ parent.views }} ViewsClicks
Tweet

{{parent.nComments}}