泛型通配符的Scala反射类型相等

泛型通配符的Scala反射类型相等,scala,generics,reflection,Scala,Generics,Reflection,我试图测试泛型类型向量和案例类构造函数的输入参数列表之间的相等性。我已经知道如何使用反射来获取参数及其类型的列表,但是当对象实例是泛型时,我无法知道如何测试对象实例和这些类型之间的相等性 以下是一个简化的示例: abstract class Foo[T] case class Bar[T](value: Seq[T]) extends Foo[Seq[T]] def getTypeTag[T: TypeTag](obj: T) = typeTag[T] // In my use case I

我试图测试泛型类型向量和案例类构造函数的输入参数列表之间的相等性。我已经知道如何使用反射来获取参数及其类型的列表,但是当对象实例是泛型时,我无法知道如何测试对象实例和这些类型之间的相等性

以下是一个简化的示例:

abstract class Foo[T]
case class Bar[T](value: Seq[T]) extends Foo[Seq[T]]

def getTypeTag[T: TypeTag](obj: T) = typeTag[T]

// In my use case I have a function that can return any 
// Foo, which is why I've used the wildcarded generic here
val bar: Foo[_] = Bar[Int](Seq(2))

// In my use case I actually get the type for a parameter list
// of a case class constructor, but putting this here for simplicity
val bar2 = Bar(Seq(1))
var barType = getType(bar2)
我希望能够测试barType类型,但这是我能得到的最接近的。我不确定如何获得具有指定泛型值的类型签名

scala>runtimeMirror(barClass.getClassLoader).classSymbol(barClass).toType
res112: reflect.runtime.universe.Type = Bar[T]

scala> getType(bar2)
res113: reflect.runtime.universe.Type = Bar[Int]

我对Scala(通常是JVM反射)非常陌生,因此感谢您的帮助。

您可以为所有希望使用的类型创建特征作为父对象,然后在运行时使用模式匹配来获得正确的对象类型。Scala具有非常强大的模式匹配功能

此链接可能有用: