从scala宏注释中反映注释类?

时间:2015-05-16 11:43:42

标签: scala reflection annotations scala-macros

有没有办法通过反射从宏实现中访问宏注释的构造函数声明?例如,当我定义这个宏注释时:

class Component(x: String, y: Int = 0) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro ComponentMacro.impl
}

是否可以在宏实现中反映Component?当我使用类似的东西时:

class ComponentMacro(val c: whitebox.Context) {
  import c.universe._

  def impl(annottees: c.Expr[Any]*) = {
    /* ... */
    val t = typeOf[Component] // throws exception
  }
}

编译器在宏扩展期间抛出错误。

1 个答案:

答案 0 :(得分:0)

您可以使用c.prefix.tree,如下例所示:

class ComponentMacro(val c:  scala.reflect.macros.whitebox.Context) {
  import c.universe._

  def impl(annottees: c.Expr[Any]*): c.Expr[Any] = {
    val annottation = c.prefix.tree
    annottation match {
      case q""" new $className(..$params) """ => println(s"className=$className, x=$params")
    }
    c.Expr(q""" case class Test() """)
  }
}

对于这个带注释的类:

@Component("FooBar", 5)
case class Test()

将输出:

Warning:scalac: className=Component, x=List("FooBar", 5)
相关问题