1
trait Bar
trait Dar

trait Foo {  self : Bar with Dar =>

}

trait Child extends Foo

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

4

1 回答 1

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

如果您想进一步检查 self 类型,可以将其与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)
于 2013-07-06T14:52:36.023 回答