假设我有一个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])
答案 0 :(得分: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 <:< _)
}
答案 1 :(得分:0)
以下似乎是正确的,虽然我猜它会因为更高的kinded类型而失败:
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 <:< _)
}