如何使用Scala反射来查找自我类型特征?

时间:2013-07-05 21:44:10

标签: scala scala-2.10

trait Bar
trait Dar

trait Foo {  self : Bar with Dar =>

}

trait Child extends Foo

如何使用新的反射API从typeOf [Foo]或typeOf [Child]中查找其自身类型是否具有Bar和Dar特征?

1 个答案:

答案 0 :(得分:1)

Welcome to Scala version 2.10.1 (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_10).
Type in expressions to have them evaluated.
Type :help for more information.

scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._

scala> :paste
// Entering paste mode (ctrl-D to finish)

trait Bar
trait Dar

trait Foo {  self : Bar with Dar =>

}

// Exiting paste mode, now interpreting.

defined trait Bar
defined trait Dar
defined trait Foo

scala> val selfTypeOfFoo = typeOf[Foo].typeSymbol.asClass.selfType
selfTypeOfFoo: reflect.runtime.universe.Type = Foo with Bar with Dar

如果您想进一步检查自我类型,可以将其与RefinedType匹配:

scala> val RefinedType(parents, _) = selfTypeOfFoo
parents: List[reflect.runtime.universe.Type] = List(Foo, Bar with Dar)

scala> val RefinedType(innerParents, _) = parents(1)
innerParents: List[reflect.runtime.universe.Type] = List(Bar, Dar)