0

I have a few reflection methods i'm using:

  def typeMirror = runtimeMirror(this.getClass.getClassLoader)
  def instanceMirror = typeMirror.reflect(this)
  def members = instanceMirror.symbol.typeSignature.members

From members i'm trying to do something like this (I understand this is not correct, but i've tried various ways without success):

  def modelMembers = members.filter(member => member.typeSignature == Model)

Where Model is the super class. The problem is I can only seem to figure out the sub classing typeSignature. How can i filter the members based on if they're a subclass of Model?

4

3 回答 3

1

有一个非常方便的<:<运算符来测试一个类型是否是另一个类型的子类型:

def modelMembers = members.filter(_.typeSignature <:< typeOf[Model])

注意:这只会得到你的字段,而不是Model返回类型的方法。

例子:

trait A
class B extends A
class C extends A

class X {
  val hello: C = null
  var world: B = null
}

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

scala> typeOf[X].members.filter(_.typeSignature <:< typeOf[A])
res0: Iterable[Symbol] = SynchronizedOps(variable world, value hello)
于 2013-11-07T14:24:17.393 回答
0

发现了一点小窍门。如果有人知道更具体的方式,我很乐意看到它。

  def modelMembers = {
    val filtered = members.filter(member => member.typeSignature.baseClasses.size > 0 && member.isTerm && !member.isMethod)
    filtered.filter(_.typeSignature.baseClasses.exists(_.name.toString == "Model"))
  }
于 2013-11-05T01:50:58.033 回答
0

它似乎对我有用?

package load.data

abstract class AbstractPoint
case class Point() extends AbstractPoint

object ModelTest {
  def main(arg: Array[String]) =
    {
      val li = List(new Point())
      assert(li.filter(_.isInstanceOf[AbstractPoint]).length == 1)
    }
}
于 2013-11-04T20:28:39.873 回答