Mechanism to obtain method caller
My principal problem is how to find out whitch object t开发者_StackOverflow社区ype called specific method.
Is out there any solution that do no use stack trace ?
If not why such information are not avaiable ? it could be very helpfull.
Is out there any solution that do no use stack trace ?
Basically, no. Certainly, there is no good solution that doesn't use exception objects and stack traces under the hood. (However, you don't need to parse the stack trace text. You can get hold of the array of StackFrame objects that contain the same information.)
In theory, you could avoid using the stacktrace mechanisms by passing an extra parameter to say who the caller is. However this is complicated and really messes up your code if you do it by hand, and problematic if you try to do it automatically.
If not why such information are not available ?
Because:
making the information available cheaply is going to cause ordinary method calls to be more expensive due to necessary changes to the method call/return "protocol",
in general, it is a bad idea for the behavior of a method to depend on what method called it, and
the stack trace mechanism does the job anyway, especially if you are only capturing the calling method for diagnostic / tracing purposes.
Throw an exception, catch it, then call the exception's getStackTrace()
method which returns an array of StackTraceElement
s
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/StackTraceElement.html http://download.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace()
If the method is yours, you may add a Object parameter in your method, to which you pass your calling class/object when you call the method.
For instance:
public class MethodClass
{
public static void someMethod(int arg1, Object caller)
{
// should print "MyCallingClass":
System.out.println("Calling class is: " + caller.getClass().getName());
}
}
public class MyCallingClass
{
public MyCallingClass()
{
//...
}
public void myCaller()
{
MethodClass.someMethod(123, this);
}
}
Edit: replaced type of caller
parameter in someMethod
from Class
to Object
, so it should now work.
精彩评论