不。抽象类(或特征)上的宏注释只能更改此类(特征)及其伴随对象的AST。您不能更改父母,子女,兄弟姐妹等。这样做是为了使宏注释在这种意义上是本地的。
此外,如果特征不是密封的,则甚至在编译时也不知道其子类。
如果将类(特征)和子类嵌套到某个对象中,则可以注释该对象。
如果要修改任意树,则可能需要通过Scalameta进行编译器插件或代码生成(源代码的生成)。
我想在您的用例中,您可以将宏注释替换为def宏
import scala.language.experimental.macros
import scala.reflect.macros.blackbox
def numArgs[A]: Int = macro impl[A]
def impl[A: c.WeakTypeTag](c: blackbox.Context): c.Tree = {
import c.universe._
val numArgs = weakTypeOf[A].typeSymbol.asClass.primaryConstructor.asMethod.paramLists.flatten.length
q"$numArgs"
}
class A(i: Int,s: String)
numArgs[A] // 2
或Shapeless(如果子类是案例类)
import shapeless.ops.hlist.Length
import shapeless.ops.nat.ToInt
import shapeless.{::,Generic,HList,HNil,Nat}
def numArgs[A] = new PartiallyApplied[A]
class PartiallyApplied[A] {
def apply[L <: HList,N <: Nat]()(implicit gen: Generic.Aux[A,L],length: Length.Aux[L,N],toInt: ToInt[N]): Int = toInt()
}
case class A(i: Int,s: String)
numArgs[A]() // 2
本文链接:https://www.f2er.com/3121595.html