我是否可以在正在注释的变量 (val/var) 的主体中访问注释参数的值



在我的项目中,程序员可以通过以下方式注释类的某些字段作为预测

class Foo() {
  @prediction('p1) var quality = // access 'p1 here
}

在预测注释的定义中给出了一个符号,该注释表示其 id(在本例中,质量的 id 为 'p1(。

我的问题:我想在质量变量的实现中访问该符号的值。我认为这可以通过使用宏来实现,但我无法实现它。

的问题:我如何实现这一点(允许宏(?

是的,你可以。尝试将prediction作为宏注释

class Foo() {
  @prediction('p1) var quality = {
    println(access) //'p1
  }
}
import scala.annotation.{StaticAnnotation, compileTimeOnly}
import scala.language.experimental.macros
import scala.reflect.macros.whitebox
@compileTimeOnly("enable macro paradise to expand macro annotations")
class prediction(s: Symbol) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro predictionMacro.impl
}
object predictionMacro {
  def impl(c: whitebox.Context)(annottees: c.Tree*): c.Tree = {
    import c.universe._
    val symb = c.prefix.tree match {
      case q"new prediction($s)" => s
    }
    annottees match {
      case q"$mods var $tname: $tpt = $expr" :: _ =>
        q"""$mods var $tname: $tpt = {
            val access = $symb
            $expr
          }"""
    }
  }
}

最新更新