在Scala 2.9.x中,我编写了func函数,该函数使我返回执行func()的函数的名称,例如 FUNC C预处理器宏。我了解在Scala2.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")
}
最佳答案
import scala.reflect.macros.Context
import scala.language.experimental.macros
def impl(c: Context) = {
import c.universe._
c.enclosingMethod match {
case DefDef(_, name, _, _, _, _) =>
c.universe.reify(println(c.literal(name.toString).splice))
case _ => c.abort(c.enclosingPosition, "no enclosing method")
}
}
scala> def printEnclosingMethod = macro impl
defined term macro printEnclosingMethod: Unit
scala> def foo = printEnclosingMethod
foo: Unit
scala> foo
foo
scala> printEnclosingMethod
<console>:32: error: no enclosing method
printEnclosingMethod
^
关于scala - Scala 2.10中的__FUNC__宏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14114700/