转换斯卡拉反射MethodMirror Scala的功能(Convert Scala Reflect

2019-11-05 11:18发布

我想创建的,这将在星火据帧操作方法序列。 目前我明确地创建这个序列在运行时:

val allFuncs: Seq[DataFrame => DataFrame] = Seq(func1, func2, func3)
def func1(df: DataFrame): DataFrame = {}
def func2(df: DataFrame): DataFrame = {}
def func3(df: DataFrame): DataFrame = {}

我添加的功能,它允许开发者添加的注释和我创建MethodMirrors的SEQ从它像这样,但我想getMyFuncs返回一个Seq[(DataFrame => DataFrame)]

  def getMyFuncs(): Seq[(DataFrame => DataFrame)] = {
    // Gets anything with the @MyFunc annotation
    val listOfAnnotations = typeOf[T].members.flatMap(f => f.annotations.find(_.tree.tpe =:= typeOf[MyFunc]).map((f, _))).toList
    val rm = runtimeMirror(this.getClass.getClassLoader)
    val instanceMirror = rm.reflect(this)
    listOfAnnotations.map(annotation =>   instanceMirror.reflectMethod(annotation._1.asMethod)).toSeq
}

@MyFunc
def func1(df: DataFrame): DataFrame = {}
@MyFunc
def func2(df: DataFrame): DataFrame = {}
@MyFunc
def func3(df: DataFrame): DataFrame = {}

然而,返回的SEQ getMyFuncsSeq[reflect.runtime.universe.MethodMirror]Seq[(DataFrame => DataFrame)] 。 这是预期,但不输出,我需要。 有什么办法给MethodMirrors转换成Scala的功能?

Answer 1:

尝试映射:

val getMyFuncs: Seq[reflect.runtime.universe.MethodMirror] = ???
val getMyFuncs1: Seq[DataFrame => DataFrame] = 
  getMyFuncs.map(mirror => (dataFrame: DataFrame) => mirror(dataFrame).asInstanceOf[DataFrame])

即创建lambda表达式使用手动reflect.runtime.universe.MethodMirror#apply(..)



文章来源: Convert Scala Reflection MethodMirror to Scala Function