Scala 我是否可以访问要注释的变量(val/var)主体中注释的参数值?
在我的项目中,程序员可以通过以下方式将类的某些字段注释为预测:Scala 我是否可以访问要注释的变量(val/var)主体中注释的参数值?,scala,macros,annotations,var,scala-macros,Scala,Macros,Annotations,Var,Scala Macros,在我的项目中,程序员可以通过以下方式将类的某些字段注释为预测: class Foo() { @prediction('p1) var quality = // access 'p1 here } 在表示其id的预测注释的定义中给出了一个符号(在这种情况下,质量id为“p1”) 我的问题是:我想在质量变量的实现中访问该符号的值。我认为这可以通过使用宏来实现,但我无法实现它 我的问题:我如何实现这一点(允许使用宏)?是的,您可以。尝试进行预测a 我认为您需要类似于基于注释的依赖项注入的东西。
class Foo() {
@prediction('p1) var quality = // access 'p1 here
}
在表示其id的预测注释的定义中给出了一个符号(在这种情况下,质量id为“p1”)
我的问题是:我想在质量变量的实现中访问该符号的值。我认为这可以通过使用宏来实现,但我无法实现它
我的问题:我如何实现这一点(允许使用宏)?是的,您可以。尝试进行
预测
a
我认为您需要类似于基于注释的依赖项注入的东西。
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
}"""
}
}
}