我可以在被注释的变量 (val/var) 的主体中访问注释参数的值吗?

Can I access the value(s) of the argument(s) of an annotation in the body of the variable (val/var) that is being annotated?

在我的项目中,程序员可以通过以下方式将 class 的某些字段注释为 prediction :

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

在预测标注的定义中给出了一个Symbol,表示其id(本例中quality的id为'p1).

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

我的问题:如何实现(允许使用宏)?

是的,你可以。尝试让 prediction 变成 macro annotation

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
          }"""
    }
  }
}