简体   繁体   English

如何从MemberScope反射中找到超类

[英]How to find super class from MemberScope reflection

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. 其中Model是超类。 The problem is I can only seem to figure out the sub classing typeSignature. 问题是我似乎只能弄清楚子类typeSignature。 How can i filter the members based on if they're a subclass of Model? 如何根据成员是Model的子类来过滤成员?

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. 注意 :这只会为您提供字段,而不是具有Model返回类型的方法。

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)

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM