Question

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?

Was it helpful?

Solution

There is a very handy <:< operator to test if a type is a subtype of another:

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

Note: this will only get you fields, not methods with Model return type.

Example:

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)

OTHER TIPS

it does seem to work for me?

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)
    }
}

Found a little bit of a hack. If anyone knows a more concrete way I would love to see it.

  def modelMembers = {
    val filtered = members.filter(member => member.typeSignature.baseClasses.size > 0 && member.isTerm && !member.isMethod)
    filtered.filter(_.typeSignature.baseClasses.exists(_.name.toString == "Model"))
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top