如何使用 Scala 宏在具有泛型类型参数的对象上调用函数?

How to call a function on an object with a generic type parameter using scala macros?

考虑以下两个类,它们都有一个parseFrom函数。

class X {}
object X {
  def parseFrom(b: Array[Byte]): String = "Hello"
}

class Y {}

object Y {
  def parseFrom(b: Array[Byte]): String = "HelloY"
}

我想写一个宏: getParseFrom[X] 将 return X.parseFrom 函数。

这是我目前拥有的:

import scala.reflect.macros.whitebox.Context

def getParseFromImpl[T: c.WeakTypeTag](c: Context): c.Tree = {
  import c.universe._
  val tpe = weakTypeOf[T]

  q"""
     $tpe.parseFrom(_)
   """
}

def getParseFrom[T]: Array[Byte] => String = macro getParseFromImpl[T]

scala 2.12 中的 scala 宏是否可行?

尝试

q"""
  ${tpe.typeSymbol.companion}.parseFrom(_)
"""