Scala反射在运行时从名称解析通用特征

时间:2016-08-05 08:12:24

标签: scala generics reflection

我有两个特征,它们的实例对象定义如下:

package reflection

trait Monoid[T] {
  def id: T
  def op(lhs: T, rhs: T): T
}

trait ADTHelper[T]{
  type V
  def create(value: V): T
  def get(adt: T): Any
}

case class Avg(avg: Double, n: Int)

object AvgMonoid extends Monoid[Avg] with ADTHelper[Avg]{
  override def id: Avg = Avg(0, 0)

  override def op(lhs: Avg, rhs: Avg): Avg =
    Avg( (lhs.avg * lhs.n + rhs.avg * rhs.n)/(lhs.n + rhs.n), lhs.n + rhs.n)

  override type V = Double
  override def create(value: Double): Avg = Avg(value, 1)
  override def get(adt: Avg): Any = adt.avg
}

object MinMonoid extends Monoid[Double] with ADTHelper[Double]{
  override def id: Double = Double.MaxValue

  override def op(lhs: Double, rhs: Double): Double = if(lhs < rhs) lhs else rhs

  override type V = Double

  override def create(value: Double): Double = value

  override def get(adt: Double): Any = adt
}

我希望在运行时从名称中获取monoid实例。例如,如果我说"min",我想要MinMonoid个对象,"avg"应该给AvgMonoid个对象,等等。所以我有以下设置:

object Test extends App {

  val AGGREGATORS_NAME_DICT = Map(
    "avg" -> "reflection.AvgMonoid",
    "min" -> "reflection.MinMonoid",
    "max" -> "reflection.MaxMonoid"
  )
  val AGGREGATORS_ADT_DICT = Map(
    "avg" -> "reflection.Avg",
    "min" -> "scala.Double",
    "max" -> "scala.Double"
  )

  val mirror = runtimeMirror(getClass.getClassLoader)

  def stringToTypeTag[A](name: String): TypeTag[A] = {
    val tpe = mirror.staticClass(name).selfType
    TypeTag(mirror, new api.TypeCreator {
      def apply[U <: api.Universe with Singleton](m: api.Mirror[U]) =
        if (m eq mirror) tpe.asInstanceOf[U#Type]
        else throw new IllegalArgumentException(s"Type tag defined in $mirror cannot be migrated to other mirrors.")
    })
  }

  def resolve[T](fname: String): Option[Monoid[T] with ADTHelper[T]] = for {
    monoidName <- AGGREGATORS_NAME_DICT.get(fname)
    adtName <- AGGREGATORS_ADT_DICT.get(fname)
    tag <- Option{stringToTypeTag[T](adtName)}
    instance <- Option {
      mirror
        .reflectModule(mirror.staticModule(monoidName))
        .instance
        .asInstanceOf[Monoid[T] with ADTHelper[T]]
    }
  } yield instance
}

现在的问题是: 我能做到:

println(resolve("min").get.op(1.0, 2.0))

但我不能这样做:

val monoid = resolve("min").get
println(monoid.op(1.0, 2.0))

因为稍后monoid的类型为Monoid[Nothing] with ADTHelper[Nothing]。我无法使用我提出的T方法解析trait Monoid[T]trait ADTHelper[T]的基础类型resolve。如何修改resolve函数,以便使用基础类型T解析特征?

我知道如果我使用resolve[Double](...)进行呼叫,它会起作用,但我希望这可以在运行时从AGGREGATORS_ADT_DICT解决。

1 个答案:

答案 0 :(得分:2)

在运行时解析T是不可能的,因为那时 没有T来解决!当您编写resolve("min")时,编译器具有以在编译期间确定其类型参数。并且由于这些论点并未告诉T任何内容,并且上下文没有提供预期类型(例如val monoid: Monoid[Double] = resolve("min")),它将推断{{1}请注意Nothing的代码在这里根本不重要,只有它的类型签名。

您可以使resolve成为宏,从而在宏的运行时确定resolve,即使用此宏的程序的编译时间。但这只适用于您在编译时知道名称的情况(例如,它是一个文字字符串)。