如何获得宏认证者的(“当前”)类型?宏认证者的类型
import scala.annotation.StaticAnnotation
import scala.reflect.macros._
import language.experimental.macros
class myself extends StaticAnnotation {
def macroTransform(annottees: Any*) = macro myselfMacro.impl
}
object myselfMacro {
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
val a = annottees.head
println(s"static type = ${a.staticType}")
println(s"actual type = ${a.actualType}")
c.Expr[Any](Literal(Constant()))
}
}
测试:
@myself class Foo
输出:
static type = Nothing
actual type = null
我想要的类型的原因是,我想用它作为一个类型参数,例如Bar[Foo]
编辑:
好了,所以我认为正确的做法是这样的:
def impl(c: Context)(annottees: c.Expr[Any]*): c.Expr[Any] = {
import c.universe._
val v = annottees.head.asInstanceOf[ClassDef]
val tpe = v.tpe // <- tpe is null as the annotated type is not yet type checked!
val tpe2 = if (tpe == null)
c.typeCheck(v).tpe // <- fails with a compiler error (assertion failure)
else
tpe
println(s"Type of annottee: $tpe2")
???
}
但given this post by Eugene Burmako,它看起来像it is currently not possible ...
我以为宏注释并没有在2.11.x中发生。有改变吗? – wheaties
他们已经发生在2.10和2.11通过宏观天堂插件。如果我们正在谈论被纳入标准分布,那么2.10香草和2.11香草都不会有它们。 –
您能否详细说明用例?问题是,当宏注解被扩展时,被注释者没有为它创建的符号(有时它确实,但它不是给定的)。因此,它不能被符号/类型引用,只能通过树引用。当然,c.typecheck的结果会给你一些符号/类型,但它只能用于内省目的,而不能作为参考。 –