开发者

Getting info about invoking class

Is it possible to get information about class that invoking the ot开发者_开发问答her one?


class Bar{
    public Bar{}

    public String getInvokingClassInfo(){
        return "...";
    }
}

class Foo{
    public Foo(){
       Bar bar = new Bar();
       System.out.println("Invoking class is: "+bar.getInvokingClassInfo());
    }
}

How to get in the place:


System.out.println(bar.getInvokingClassInfo());

info about class that invoking (Foo) this one (Bar):

Invoking class: Foo


 StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
 String callerClassName = stackTrace[index].getClassName();

This is getting the stacktrace for the current thread. As noted in the comments, there are implementation differences, so if you fear such, you can implement something like this:

  • loop through the StackTraceElement array (using a counter variable declared outside the loop)
  • whenever you encounter the current class name and the current method, break
  • get the next element of the array - it will be the invoker. (that's what index stands for in the above code)
  • if the above doesn't provide relevant information you can always fall back to new Exception().getStackTrace()


The best (though contorted and ugly) solution I could think of would be to throw an exception inside Bar and catch it right away, then extract the caller info from its stack trace.

Update based on others' comments: you don't even need to throw and catch the exception, new Exception().getStackTrace() will do the trick.


The most robust way I can imagine is to pass "this" as an argument to B from inside A. Then B can have a look at the object, and print out its class.

Everything that fiddles with stack traces relies on things which are not guaranteed to work. The "pass-this" approach will.


In the context we used (Java 7) the only safe way to find out about the caller was the following:

private static class ClassLocator extends SecurityManager {
    public static Class<?> getCallerClass() {       
        return new ClassLocator().getClassContext()[2];
    }
}

As the API Reference says:

"protected Class[] getClassContext() Returns the current execution stack as an array of classes. The length of the array is the number of methods on the execution stack. The element at index 0 is the class of the currently executing method, the element at index 1 is the class of that method's caller, and so on."

http://docs.oracle.com/javase/7/docs/api/java/lang/SecurityManager.html#getClassContext()

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜