今天在遇到个问题,如何在callee中获取caller的信息?
搜索了一下,java提供一种如下的方法:
StackTraceElement stack[] = (new Throwable()).getStackTrace();
即可获得相应的调用栈中的信息。
方法其实类似new 一个Exception ,然后printStackTrace.......
但是有大牛说这是一个不精确的方法,java并未保证可以获取caller信息的完整;
查阅了Java文档说明:
getStackTrace
public StackTraceElement[] getStackTrace()
-
Provides programmatic access to the stack trace information printed by
printStackTrace()
. Returns an array of stack trace elements, each representing one stack frame. The zeroth element of the array (assuming the array's length is non-zero) represents the top of the stack, which is the last method invocation in the sequence. Typically, this is the point at which this throwable was created and thrown. The last element of the array (assuming the array's length is non-zero) represents the bottom of the stack, which is the first method invocation in the sequence.Some virtual machines may, under some circumstances, omit one or more stack frames from the stack trace. In the extreme case, a virtual machine that has no stack trace information concerning this throwable is permitted to return a zero-length array from this method. Generally speaking, the array returned by this method will contain one element for every frame that would be printed by printStackTrace.
-
-
Returns:
- an array of stack trace elements representing the stack trace pertaining to this throwable. Since:
- 1.4
注意红色部分:某些虚拟机在一些情况下,会省略一个或多个栈信息;而甚至在某些极端case里,这个方法甚至返回一个长度为零的数组;
可见,不可以使用这种方法来保证程序的正确运行,特别是需要根据caller来进行判断处理的需求,在这种情况下只能考虑其他的方法(譬如caller在调用前传递活着设置相关信息);
那这个方法有什么用?或许在进行调试或者Log的时候可以吧?还需要调查一番。