0

假设我有一个Type实例列表(引用类!),以及一个未知类型的运行时对象。查找对象是子类型的/类型。

import reflect.runtime.universe._

// obj _required_ to be of type Any, no compile time type available
def find(tps: List[Type], obj: Any): Option[Type] = ???

这样

sealed trait Gender
case object Male   extends Gender
case object Female extends Gender
case object Other  extends Gender

val tps = List(typeOf[Male.type], typeOf[Female.type], typeOf[Other.type])
assert(find(tps, Other).get =:= typeOf[Other.type])
4

2 回答 2

1

您需要从运行时镜像中获取Type或对应Class,然后将它们进行比较:

def find(tps: List[Type], obj: Any): Option[Type] = {
  val mirror = runtimeMirror(this.getClass.getClassLoader)
  val tpe = mirror.classSymbol(obj.getClass).toType

  tps find (tpe <:< _)
}
于 2013-06-09T15:27:41.123 回答
0

以下似乎是正确的,尽管我猜它会因更高种类的类型而失败:

import reflect.runtime.universe._
import reflect.runtime.{currentMirror => cm}

def find(tps: List[Type], obj: Any): Option[Type] = {
  val objClass = obj.getClass
  val objType  = cm.classSymbol(objClass).toType
  tps find (objType <:< _)
}
于 2013-06-09T15:27:51.823 回答