使用Scala反射,我如何提取特征mixin?

时间:2016-09-03 20:00:16

标签: scala reflection

我的示例域名:

trait Thing2[T, U] {
  val t: T
  val u: U
}
case class TwoThing[P](x: P, t: String, u: P) extends Thing2[String, P]
case class Wow2[A](a: String, b: Thing2[String, A])

val wow = Wow2("blah", TwoThing(1,"hey",2))  // <-- Reflect on this

我正在反思一个Wow2 [Int]对象,当我走的时候,我传递了b是Thing2 [String,Int]的知识。

我最终到达时反映了TwoThing [P]对象并且仍然知道它应该是Thing2 [String,Int]。我需要一些东西来关联P - &gt;因此我可以替换类型。

def lookSee( tpe:Type, superParamTypes:List[Type] ) {
  // tpe is TwoThing[P] and superParamTypes is List(String,Int)
  println(tpe)
}

这显示了输出:

[P]scala.AnyRef
        with co.blocke.scalajack.test.Thing2[String,P]
        with scala.Product
        with scala.Serializable {
  val x: P
  private[this] val x: P
  val t: String
  private[this] val t: String
  val u: P
  private[this] val u: P
  def <init>(x: P,t: String,u: P): co.blocke.scalajack.test.TwoThing[P]
  def copy[P](x: P,t: String,u: P): co.blocke.scalajack.test.TwoThing[P]
  def copy$default$1[P]: P @scala.annotation.unchecked.uncheckedVariance
  def copy$default$2[P]: String @scala.annotation.unchecked.uncheckedVariance
  def copy$default$3[P]: P @scala.annotation.unchecked.uncheckedVariance
  override def productPrefix: java.lang.String
  def productArity: scala.Int
  def productElement(x$1: scala.Int): scala.Any
  override def productIterator: Iterator[scala.Any]
  def canEqual(x$1: scala.Any): scala.Boolean
  override def hashCode(): scala.Int
  override def toString(): java.lang.String
  override def equals(x$1: scala.Any): scala.Boolean
}

我需要的所有信息都在此输出中。我看到这是一个TwoThing [P],我可以提取P.我看到特质mixin Thing2 [String,P]。并且由于superParamTypes,我仍然知道Thing2的参数将是[String,Int],所以我需要做的就是关联P - &gt;中间体

很棒... 如何从tpe中提取信息:with co.blocke.scalajack.test.Thing2[String,P]具体来说,我想要信息[String,P],以便将其与所需的参数相关联[String,Int]和&#34;解决&#34;让P到达我的用于TwoThing的参数图(P-> Int)。

1 个答案:

答案 0 :(得分:0)

假设您已经运行了代码(“Sample Domain”)来设置特征和案例类,您可以这样做:

  def decipherWow(wow: Wow2[_]): Unit = {
    val a = wow.a   // String
    val b = wow.b   // Thing2[String, _]

    val elem1type = b.t.getClass.getSimpleName  // Thing2 first element
    val elem2type = b.u.getClass.getSimpleName  // Thing2 second element

    println("Thing2 deciphered:")
    println("First element is type:  " + elem1type)
    println("Second element is type:  " + elem2type)
  }


  decipherWow(wow);

输出:

Thing2 deciphered:
First element is type:  String
Second element is type:  Integer