How to get the caller class in Java

java

Solution

You can generate a stack trace and use the informations in the StackTraceElements.

For example an utility class can return you the calling class name :

public class KDebug {
    public static String getCallerClassName() { 
        StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
        for (int i=1; i<stElements.length; i++) {
            StackTraceElement ste = stElements[i];
            if (!ste.getClassName().equals(KDebug.class.getName()) && ste.getClassName().indexOf("java.lang.Thread")!=0) {
                return ste.getClassName();
            }
        }
        return null;
     }
}

If you call `KDebug.getCallerClassName()` from `bar()`, you'll get `"foo"`.

Now supposing you want to know the class of the method calling `bar` (which is more interesting and maybe what you really wanted). You could use this method :

public static String getCallerCallerClassName() { 
    StackTraceElement[] stElements = Thread.currentThread().getStackTrace();
    String callerClassName = null;
    for (int i=1; i<stElements.length; i++) {
        StackTraceElement ste = stElements[i];
        if (!ste.getClassName().equals(KDebug.class.getName())&& ste.getClassName().indexOf("java.lang.Thread")!=0) {
            if (callerClassName==null) {
                callerClassName = ste.getClassName();
            } else if (!callerClassName.equals(ste.getClassName())) {
                return ste.getClassName();
            }
        }
    }
    return null;
 }

Is that for debugging ? If not, there may be a better solution to your problem.

Problem

I want to get the caller class of the method, i.e. ``` class foo{ bar(); } ``` In the method bar, I need to get the class name `foo`, and I found this method: ``` Class clazz = sun.reflect.Reflection.getCallerClass(1); ``` However, even though `getCallerClass` is `public`, when I try to call it Eclipse says: Access restriction: The method getCallerClass() from the type Reflection is not accessible due to restriction on required library C:\Program Files\Java\jre7\lib\rt.jar Are there any other choices?

Original source

Related problems