_FUNC__宏Scala 2.10
发布时间:2020-12-16 19:02:16 所属栏目:安全 来源:网络整理
导读:在 Scala 2.9.x中,我写了一个func函数,它给出了函数的名称,这个函数的执行类似于FUNC C预处理器宏.我明白,在Scala2.10中,我应该能够写出比抛出异常更优雅的东西来做这个工作. 我该怎么做?在此先感谢您的帮助. object TestMyLog extends App { val MatchFunc
在
Scala 2.9.x中,我写了一个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 ^ (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |