使用反射将特征实现成员纳入范围

时间:2014-09-06 03:34:56

标签: scala

我正在使用反射来解析扩展名为Component的特征的类的所有公共变量访问器,并调用以下内容:

def iterate[T <: Component : TypeTag : ClassTag](component: T) {
  ...
  ru.typeOf[T].members.filter(...)
  ...
}

但是,这仅适用于在调用期间显示实现Component trait的类类型:

val myComp: MyComponent = new MyComponent()
iterate(myComp) // works

val myComp: Component = new MyComponent()
iterate(myComp) // Doesn't work, no members of MyComponent found in scope

一个解决方案是在trait中定义实现类型(MyComponent扩展Component [MyComponent]),但是因为我正在挖掘反射,所以我想知道是否可以从特征后面访问MyComponent的变量。 / p>

1 个答案:

答案 0 :(得分:0)

我认为你可以从Type获得java.lang.Class。请参阅下面的示例。

╰─$ scala
Welcome to Scala version 2.11.2 (OpenJDK 64-Bit Server VM, Java 1.7.0_65).
Type in expressions to have them evaluated.
Type :help for more information.

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


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

trait Component {
  def parent: Int = 0
}
class MyComponent extends Component {
  def child: Int = 0
}
def printRuntimeMemberNames(component: Component) = {
  val cls = component.getClass
  val mirror = runtimeMirror(cls.getClassLoader)
  val symbol = mirror.staticClass(cls.getName)
  val tpe = symbol.toType
  val members = tpe.members
  val memberNames = members.map(_.name.decodedName.toString)
  println(memberNames.mkString(", "))
}


// Exiting paste mode, now interpreting.

import scala.reflect._
import scala.reflect.runtime.universe._
defined trait Component
defined class MyComponent
printRuntimeMemberNames: (component: Component)Unit

scala> val c: Component = new MyComponent
c: Component = MyComponent@3db7416a

scala> printRuntimeMemberNames(c)
<init>, child, parent, $init$, $asInstanceOf, $isInstanceOf, synchronized, ##, !=, ==, ne, eq, notifyAll, notify, clone, getClass, hashCode, toString, equals, wait, wait, wait, finalize, asInstanceOf, isInstanceOf