一种得到代码所在行号的方法

       RT,今天在论坛上看到有人提出这个问题,马上联想到当程序发生异常时,异常信息里面就包含了异常所在行的信息.既然这样,那我为何不再需要得到行号的地方new 一个Exception,然后分析其包含的行号信息呢?

      想法有了,剩下的就简单了,查了下Exception的相关文档,发现Throwable有个getStackTrace()的方法:

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.

 

getLineNumber

public int getLineNumber
()
Returns the line number of the source line containing the execution point represented by this stack trace element. Generally, this is derived from the LineNumberTable attribute of the relevant class file (as per The Java Virtual Machine Specification , Section 4.7.8).

 

Returns:
the line number of the source line containing the execution point represented by this stack trace element, or a negative number if this information is unavailable.


最终的代码如下:

java 代码
  1. /**    
  2.  *得到Exception所在代码的行数    
  3.  *如果没有行信息,返回-1    
  4.  */      
  5.   public   static   int  getLineNumber(Exception e){      
  6.      StackTraceElement[] trace =e.getStackTrace();      
  7.       if (trace== null ||trace.length== 0return  - 1 ;    //      
  8.       return  trace[ 0 ].getLineNumber();      
  9.  }     


使用方法如下:

java 代码
  1. System.out.println( "Current line number :" +getLineNumber( new  Exception()));     

就可以将System.out.println所在行的行号输入.

ps:根据getStackTrace说明文档的红色部分,说明getStackTrace返回内容并没有被硬性规定,因此我这种方法并不能保证在每一个JVM上都有效.但我暂时还不知道有没有其它更好的方法可以实现同样的功能.

而StackTraceElement有个getLineNumber的方法:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值