本文介绍了Groovy中的__LINE__功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Ruby或Perl中,可以通过 __ LINE __
获取当前行号。
例如:
It is possible to get current line number by __LINE__
in Ruby or Perl.For example:
print "filename: #{__FILE__}, line: #{__LINE__}"
Groovy中有相同的功能吗?
Is there the same feature in Groovy?
推荐答案
不直接,但可以通过Exception(或Throwable)堆栈跟踪来获取它。例如:
Not directly, but you can get it through an Exception (or Throwable) stack trace. For example:
StackTraceElement getStackFrame(String debugMethodName) {
def ignorePackages = [
'sun.',
'java.lang',
'org.codehaus',
'groovy.lang'
]
StackTraceElement frame = null
Throwable t = new Throwable()
t.stackTrace.eachWithIndex { StackTraceElement stElement, int index ->
if (stElement.methodName.contains(debugMethodName)) {
int callerIndex = index + 1
while (t.stackTrace[callerIndex].isNativeMethod() ||
ignorePackages.any { String packageName ->
t.stackTrace[callerIndex].className.startsWith(packageName)
}) {
callerIndex++
}
frame = t.stackTrace[callerIndex]
return
}
}
frame
}
int getLineNumber() {
getStackFrame('getLineNumber')?.lineNumber ?: -1
}
String getFileName() {
getStackFrame('getFileName')?.fileName
}
String getMethodName() {
getStackFrame('getMethodName')?.methodName
}
def foo() {
println "looking at $fileName:$lineNumber ($methodName)"
}
foo()
// ==> looking at test.groovy:39 (foo)
请注意:获取行号,文件名或像这样的方法很慢。
A word of caution though: getting the line number, file name, or method like this is very slow.
这篇关于Groovy中的__LINE__功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!