我需要检查任何对象的类型并获取相应的对象。 但是,不能通过将T传递给正常的功能参数来解析T。 您需要进行比较,直到所有类型参数都匹配为止。
trait Wrap[T]
trait Interface
trait InterfaceA extends Interface
trait InterfaceB extends Interface
object InterfaceAImpl extends Wrap[InterfaceA] with Candidate
object InterfaceBImpl extends Wrap[InterfaceB] with Candidate
trait Mediate[T <: Interface] {
val t: T = get[Wrap[T]]
}
object A extends Mediate[InterfaceA]
object B extends Mediate[InterfaceB]
def get[T: c.WeakTypeTag](c: blackbox.Context): c.Expr[Option[T]] = {
import c.universe._
// Find an object that mixes in a specific interface
// Suppose that the result is [[object A]] and [[object B]]
val detected: List[Symbol] = new CandidateExtractor[c.type](c).run[Candidate]
// This result is
// "InterfaceAImpl =:= Wrap[T]"
// "InterfaceBImpl =:= Wrap[T]"
// When called from A, it expects Wrap[InterfaceA] instead of Wrap[T]
detected.foreach(x => println(s"${x.typeSignature} =:= ${weakTypeOf[T]}"))
// Find objects that inherits Wrap [T] among objects that inherit a specific interface
val r = detected.collectFirst {
// Wrap[InterfaceA] and Wrap[T] are compared, so all false.
case x if x.typeSignature =:= weakTypeOf[T] => x
}
c.Expr[Option[T]](
q"$r"
)
}
有没有办法比较继承关系,包括泛型?
因此,我要做的是...
object A
的{{1}} = t: T
,因为它继承了InterfaceAImpl
Wrap[InterfaceA]
的{{1}} = object B
,因为它继承了t: T
因此InterfaceBImpl
无效。
必须为Wrap[InterfaceB]
和<:<(typeOf[Wrap[_])
答案 0 :(得分:0)
尝试
List(typeOf[Wrap[_]].typeSymbol, typeOf[Candidate].typeSymbol).forall(x.typeSignature.baseClasses.contains)
或
List(typeOf[Wrap[_]].typeSymbol, typeOf[Candidate].typeSymbol).forall(x.typeSignature.baseType(_) match { case _ : TypeRef => true; case NoType => false })