我想在运行时动态执行对象 X
的以 removeAt
开头的方法。
如何使用 REFLECTION Environment, Universes, and Mirrors 中描述的 scala.reflect.runtime.universe
API 来做到这一点
最佳答案
这是您问题的解决方案:
object X {
def aa = 1
def ab = 2
def removeAtX = 3
def bb = 4
def removeAtY = 5
}
val ru = scala.reflect.runtime.universe
val m = ru.runtimeMirror(getClass.getClassLoader)
val im = m.reflect(X)
val l = X.getClass.getMethods.map(_.getName).filter(_ startsWith "removeAt")
val r = l.map(y => ru.typeOf[X.type].declaration(ru.newTermName(y)).asMethod).map(im.reflectMethod(_).apply())
结果:
r: scala.collection.mutable.ArraySeq[Any] = ArraySeq(3, 5)
关于scala - 使用 scala.reflect.runtime.universe 动态调用 Scala 中对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20300584/