假设我有一个宏注释AnnProxy和以下代码:
trait MyTrait
{
def x: Int
}
@AnnProxy
class MyClass extends MyTrait
我现在需要获取MyTrait的类型,以便我可以代理它的方法。到目前为止,我的代码看起来像:
@compileTimeOnly("enable macro paradise to expand macro annotations")
class AnnProxy extends StaticAnnotation
{
def macroTransform(annottees: Any*): Any = macro IdentityMacro.impl
}
object IdentityMacro
{
def impl(c: whitebox.Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
val inputs = annottees.map(_.tree).toList
val classDef = inputs.head.asInstanceOf[ClassDef]
val superclass= // how do I get the Type of the superclass?
c.Expr[Any] {
q"""
class ${classDef.name} {
def doit() : Unit = println("doit")
}
"""
}
}
}
答案 0 :(得分:1)
你可以使用模式匹配
class SuperClass extends StaticAnnotation {
def macroTransform(annottees: Any*): Any = macro SuperClassImpl.apply
}
class SuperClassImpl(val c: Context) {
def showInfo(s: String) =
c.info(c.enclosingPosition, s.split("\n").mkString("\n |---macro info---\n |", "\n |", ""), true)
import c.universe._
def apply(annottees: c.Expr[Any]*) = {
val superClass = annottees.map(_.tree).head match {
case q"$mod class $name(..$params) extends ..$superClass { ..$body }" =>
superClass
}
showInfo(show(superClass))
q"{..$annottees}"
}
}
测试
trait AA
trait BB
trait CC
@SuperClass
class SuperClassUsing extends AA with BB with CC //when show info List(AA,BB,CC)