2015-11-30 75 views
0

的tparam的類型說我有一個宏註釋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") 
     } 
    """ 
    } 
} 
} 

回答

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) 
+0

嗨,問題是superClass.map是一個列表(_ TPE)。的空值。我認爲這與宏在運行時沒有檢查類型有關,但是如何獲取tpe以便我可以獲取tpe的方法列表? –

+1

這可以得到超級符號'c.typecheck(annottees.map(_。樹).head).symbol.asClass.baseClasses.tail' –

+0

謝謝,這個竅門 –