在编译时有效地获取java源代码中的行号

bl3*_*l3e 11 java eclipse gradle

我有一个异常类,我想在其中传递当前行号

     line 70:
     line 71: throw new 
              LightException(FailureType.NOT_FOUND,this.getClass().getName(),linenum);
Run Code Online (Sandbox Code Playgroud)

有没有办法在没有硬编码的情况下将亚麻布作为72? eclipse是否提供了在编译时被替换为硬编码行号的任何东西.所以我不必把丑陋的硬编码行号

class LightException(FailureType type,String className,int lineNum)  extends RuntimeException 
{

LightException(FailureType type,String className,int lineNum){..
//
}

@Override
@Override public Throwable fillInStackTrace() { 
return this;
 }
}
Run Code Online (Sandbox Code Playgroud)

我不需要记录整个堆栈跟踪,并且不必为所有异常填充堆栈跟踪.我想添加引发异常的行号. 任何可以在编译时解析为常量的代码?

如果没有那么我可以写一个简单的预处理我的代码,它可以读取行并用行号替换一个特殊的常量_my_line_num,但应该存在一些东西.

我觉得像gradle这样的构建工具可以做到这一点.

Jeg*_*egg 0

我不确定这是否是一个好的解决方案,但您可以将其放置:

int linenumber = Thread.currentThread().getStackTrace()[2].getLineNumber();
Run Code Online (Sandbox Code Playgroud)

作为异常承包商中的参数并根据需要显示它。