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

时光毁灭记忆、已成空白 提交于 2019-12-19 08:59:09

问题


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!


回答1:


You need to write runtimeMirror.reflect(<instance of MyClass>).reflectModule(objASymbol). Plain reflectModule won't do, because some reflective operations on objA (e.g. 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.



来源:https://stackoverflow.com/questions/11084408/scala-reflection-error-this-is-an-inner-module-use-reflectmodule-on-an-instanc

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!