DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Reflection - Find The Caller

  • submit to reddit
        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) {

<b>Program Output</b>:
class com.test.reflection.CallerIDTest