【问题标题】:Scala reflection type equality of generic wildcard通用通配符的Scala反射类型相等
【发布时间】: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


    【解决方案1】:

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

    此链接可能有用:http://www.cakesolutions.net/teamblogs/ways-to-pattern-match-generic-types-in-scala

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      • 1970-01-01
      • 2022-12-07
      • 2020-07-10
      • 1970-01-01
      • 2015-03-22
      相关资源
      最近更新 更多