六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 781|回复: 0

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

[复制链接]

升级  29.33%

24

主题

24

主题

24

主题

秀才

Rank: 2

积分
94
 楼主| 发表于 2013-1-29 23:54:12 | 显示全部楼层 |阅读模式
       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. 
<span style="font-family: Arial;">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.
最终的代码如下:
<div class="code_title">java 代码
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表