我有一个ClassSymbol
,想要生成一个零参数方法throwing ???
。这是我的尝试:
假设这object Test
是我们拥有的类型ClassSymbol
。
一世。
val sym = //the ClassSymbol
val tpe = tq"$sym.type"
q"def foo(): $tpe = ???"
结果:
[error] stable identifier required, but Test.type found.
二。
val sym = //the ClassSymbol
val tpe = tq"${sym.name}.type"
q"def foo(): $tpe = ???"
结果:
[error] found : c.universe.TypeName
[error] required: c.universe.TermName
[error] val tpe = tq"${sym.name}.type"
三,
val sym = //the ClassSymbol
val tpe = tq"${TermName(sym.name.toString)}.type"
q"def foo(): $tpe = ???"
结果:
Compiles successfully
所以我最终使用了看起来很吓人的方法III。
ClassSymbol
在准引用中使用“本地”方法吗?
我们可以为您省钱
val tpe = tq"${sym.name.toTermName}.type"
这类似于III,但没有手动处理字符串。
也不要忘记,除了准引用之外,您始终可以使用手动解析来构建树
val tree = tb.parse(s"def foo(): ${sym.name}.type = ???") // for macros c.parse instead of tb.parse
关于“本机”方式,现在最好使用 ModuleSymbol
val sym = rm.moduleSymbol(Test.getClass)
要么
val sym = typeOf[Test.type].termSymbol.asModule
而不是 ClassSymbol
val sym0 = rm.classSymbol(Test.getClass)
要么
val sym0 = typeOf[Test.type].typeSymbol.asClass
测试:
val tpe = tq"$sym.type"
val tree = q"def foo(): $tpe = ???"
tb.typecheck(tree) // no exception
我使用了运行时反射,但是对于宏来说却类似。
如果您已经有一个ClassSymbol
,可以将其转换为ModuleSymbol
val sym = sym0.companionSymbol // not sym0.companion but .companionSymbol is deprecated
要么
val sym = sym0.asInstanceOf[scala.reflect.internal.Symbols#ClassSymbol].sourceModule.asInstanceOf[ModuleSymbol]
要么
val sym = sym0.owner.info.decl(sym0.name.toTermName)
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句