3

Possible Duplicate:
In Java, how do i find the caller of a method using stacktrace or reflection?

I'm just curious. I was requesting that feature sometimes, but then I solved it with more code. (the calling class said its name while calling the method)

Community
  • 1
  • 1
OneWorld
  • 17,512
  • 21
  • 86
  • 136

2 Answers2

9
private Class getCallingClass() {
    return new SecurityManager() {
       protected Class[] getClassContext(){return super.getClassContext();} 
    }.getClassContext()[2];
}  

OR

public class Foo {

    public static final void main(final String[] args) {

        test();
    }

    private static void test() {

        Throwable e = new Throwable();

        StackTraceElement[] elements = e.getStackTrace();
        System.out.println(elements.length > 1 ? elements[1].toString() : "(no caller)");
    }
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • I don't think you even need to call `fillInStackTrace`: according to the [docs](http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#Throwable%28%29), the constructor calls it for you. – casablanca Oct 11 '10 at 16:20
1

You can do it using 'fake exception', even though this trick feels kinda dirty.

    try {
        throw new RuntimeException();
    } catch (RuntimeException e) {
        System.out.println(e.getStackTrace()[1]);
    }

getStackTrace returns an array of StackTraceElement objects, you can check API to see what you can do with them.

Nikita Rybak
  • 67,365
  • 22
  • 157
  • 181