【发布时间】:2017-03-16 17:34:22
【问题描述】:
我正在尝试测试泛型类型向量与案例类构造函数的输入参数列表之间的相等性。我已经弄清楚如何使用反射来获取参数列表及其类型,但是当对象实例是泛型时,我无法弄清楚如何测试对象实例与这些类型之间的相等性。
这是一个简化的例子:
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)
我希望能够测试 bar 的类型是 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 generics reflection