簡體   English   中英

使用反射將特質實現成員納入范圍

[英]Bringing trait implementation members into scope using reflection

我正在使用反射來解析來自類的所有公共變量訪問器,這些類通過以下調用擴展了名為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

一種解決方案是在特征中定義實現類型(MyComponent擴展了Component [MyComponent]),但是由於無論如何我都在進行反思,我想知道MyComponent的變量是否可以從特征后面訪問。

我認為您可以從java.lang.Class獲取Type 請參見下面的示例。

╰─$ 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM