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

阅读更多

       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== 0 return  - 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的方法:

你可能感兴趣的:(Eclipse,JVM,IDE,Access)