在斯卡拉2.9.x中,我写了func函数,它给了我函数的名称,func()被执行,就像FUNC C预处理宏。我明白,在Scala2.10中,我应该能够写出比投掷异常更优雅的东西来完成这项工作。__FUNC__宏在斯卡拉2.10
我该怎么办?在此先感谢您的帮助。
object TestMyLog extends App {
val MatchFunc = """(.+)\(.+""".r
def func(i_level: Int): String = {
val s_rien = "functionNotFound"
try {
throw new Exception()
} catch {
case unknwn => unknwn.getStackTrace.toList.apply(i_level).toString match {
case MatchFunc(funcs) => funcs.split('.').toList.last
case _ => s_rien
}
} finally {
s_rien
}
}
def tracedFunction1 = func(1)
def tracedFunction2 = func(1)
println(tracedFunction1)
assert(tracedFunction1=="tracedFunction1")
println(tracedFunction2)
assert(tracedFunction2=="tracedFunction2")
}
你甚至可以得到一个堆栈跟踪不会产生异常:有上条条的的getStackTrace()方法,所以你可以做Thread.currentThread()getStackTrace.toList –