0

我正在使用宏注释来生成代码。我想根据额外的字符串参数来改变它的行为。所以它会为相同的代码产生不同的结果。我密切关注仅涵盖最简单用法的宏注释指南。

@myMacros
class MyClass {
}

这就是我现在使用宏的方式。以及我想要实现的目标:

@myMacros(name : String)
class MyClass {
}
4

1 回答 1

1

你可以使用宏应用程序

class AnnotationPassVal(val name: String) extends StaticAnnotation {
  def macroTransform(annottees: Any*): Any = macro AnnotationPassValImpl.apply
}

class AnnotationPassValImpl(val c: Context) {

  import c.universe._

  def showInfo(s: String) =
    c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true)

  def apply(annottees: c.Expr[Any]*) = {
    val a = c.macroApplication

    //look macroApplication is what 
    showInfo(show(a))


    val AnnotationName: Tree = a match {
      case q"new AnnotationPassVal(name = $name).macroTransform(..$a)" =>
        name: Tree
    }

    showInfo(show(AnnotationName))
    q"""{..$annottees}"""
  }
}

测试

@AnnotationPassVal(name = "hello")
class AnnotationPassValTest //when show info "hello"
于 2015-11-30T14:51:57.473 回答