0

我需要在应用程序中的一些其他方法中添加一个方法。他们有很多。除了直接的方法——手动将方法调用插入每个方法之外,还有什么明智的方法可以做到这一点?

4

1 回答 1

4

请参阅此答案以使用def macros.

使用宏注释实现:

import scala.reflect.macros.Context
import scala.language.experimental.macros

def wrappedImpl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
  import c.universe._
  import scala.reflect.internal.Flags._

  object DefMods{
    def unapply(mods: Modifiers): Option[Modifiers] = {
      val fs = mods.flags.asInstanceOf[Long]
      if ((fs & DEFERRED) == 0 && (fs & STABLE) == 0) Some(mods)
      else None
    }
  }

  def wrap(t: Tree) = t match {
    case DefDef(DefMods(mods), name, tparams, vparams, tpt, body) if name != nme.CONSTRUCTOR =>
      DefDef(mods, name, tparams, vparams, tpt,
             q"""
               println("before")
               val res = $body
               println("after")
               res""")
    case x => x
  }

  def transform(t: Tree) = t match {
    case ClassDef(mods, name, tparams, Template(parents, self, methods)) =>
      ClassDef(mods, name, tparams, Template(parents, self, methods.map{wrap(_)}))
    case x => x
  }

  c.Expr[Any](Block(annottees.map(_.tree).map(transform(_)).toList, Literal(Constant(()))))
}

import scala.annotation.StaticAnnotation
class wrapped extends StaticAnnotation {
  def macroTransform(annottees: Any*) = macro wrappedImpl
}

您必须为准引号使用编译器插件

用法:

@wrapped class Test {
  def test() = println("test")
}

scala> new Test().test()
before
test
after
于 2013-11-14T12:02:07.733 回答