java中callee获取caller

今天在遇到个问题,如何在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的时候可以吧?还需要调查一番。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值