如何在基类中获取带参数的类型

时间:2017-09-20 06:26:33

标签: scala reflection

是否可以在基类中获取完整类型(带有类型参数)。以下示例说明了问题。见TODO:

import scala.reflect.api.Types

abstract class BaseClass {
  def getType: Type = ???  //TODO how to implement
}

case class Child1[M](model: M) extends BaseClass

case class Child2(p: Int) extends BaseClass

...

val c1 = Child1("Hello")
val c2 = Child2(10)

val xs = List(c1, c2)

xs foreach { e: BaseClass =>
  println(e.getType) 
}

// out:
// com.project.Child1[java.lang.String]
// com.project.Child2
// ...

2 个答案:

答案 0 :(得分:2)

您可以将类型参数添加到基类:

abstract class BaseClass[A: TypeTag] {
  def getType = s"${getClass.getName}[${typeOf[A]}]"
}

case class Child1[M: TypeTag](model: M) extends BaseClass[M]
case class Child2(p: Int) extends BaseClass[Unit]

...

xs foreach {e => println(e.getType)}

答案 1 :(得分:1)

我可以为您提出下一个解决方案:

trait BaseClass {
  val realType: Any

  def getType: String = realType.toString()
}

case class Child1[M: TypeTag](model: M) extends BaseClass {
  override val realType = typeTag[Child1[M]]

}

case class Child2(p: Int) extends BaseClass {
  override val realType = typeTag[Child2]
}

它不会产生你想要的结果,但非常接近。

val xs = Seq[BaseClass](Child1[String](""), Child2(1))
xs.foreach { e => println(e.getType) }

给出下一个输出

TypeTag[test.Child1[String]]
TypeTag[test.Child2]