Scala reflection error: this is an internal module, use mirrorModule in an instance of Mirror to get its ModuleMirror

Following this question , I am trying to figure out how to call a method on an object. Relevant definitions:

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

I got Symbol for objA as follows:

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

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

 val objASymbol = stuff.head.asModuleSymbol 

Then I tried based on this other question :

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

As a result, an error message appeared:

 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 cannot understand what this error message says!

+4
source share
1 answer

You need to write runtimeMirror.reflect(<instance of MyClass>).reflectModule(objASymbol) . Plain reflectModule will not work because some reflective operations on objA (e.g. getting its instance) require an external instance.

Unfortunately, your use case will not work even if you write it correctly, because M4 only supports static objects: https://issues.scala-lang.org/browse/SI-5498 . We will do this before 2.10.0-final.

+6
source

All Articles