Reputation: 1867
Is it possible to get information about class that invoking the other 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
Upvotes: 1
Views: 263
Reputation: 6219
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()
Upvotes: 0
Reputation: 75426
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.
Upvotes: 2
Reputation: 597412
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:
StackTraceElement
array (using a counter variable declared outside the loop)break
index
stands for in the above code)new Exception().getStackTrace()
Upvotes: 8
Reputation: 116306
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.
Upvotes: 3