Scala reflection error: this is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror

Following up on this question, I'm trying to figure out how to call a method on an object. The relevant definitions are:

trait ThirdParty { def invoke = println("right") }
trait WeatherIcon { def invoke = println("wrong") }
class MyClass {
    object objA extends ThirdParty
    object objB extends WeatherIcon
}

I got a Symbol for objA like this:

import reflect.runtime.universe._

val stuff = typeOf[MyClass].members.filter(_.isValue).filter(_.typeSignature <:< typeOf[ThirdParty])

That returns an Iterable with a single element, so let's say:

val objASymbol = stuff.head.asModuleSymbol

I then tried, based on this other question, this:

val mirror = runtimeMirror(getClass.getClassLoader)
mirror.reflectModule(objASymbol)

Which resulted in the error message quoted on the subject:

java.lang.Error: this is an inner module, use reflectModule on an InstanceMirror to obtain its ModuleMirror
    at scala.reflect.runtime.JavaMirrors$JavaMirror.reflectModule(JavaMirrors.scala:118)
    at scala.reflect.runtime.JavaMirrors$JavaMirror.reflectModule(JavaMirrors.scala:60)

The problem is that I can't figure out what this error message is telling me to do!


You need to write runtimeMirror.reflect(<instance of MyClass>).reflectModule(objASymbol) . Plain reflectModule won't do, because some reflective operations on objA (eg getting its instance) require an outer instance.

Unfortunately, your use case won't work even if you write it right, because M4 only supports static objects: https://issues.scala-lang.org/browse/SI-5498. We'll implement this before 2.10.0-final.

链接地址: http://www.djcxy.com/p/76522.html

上一篇: 通过Scala反射查找封闭的实例(如果有的话)

下一篇: Scala反射错误:这是一个内部模块,在InstanceMirror上使用reflectModule来获取其ModuleMirror