I am writing a DSL which describes a structure. The DSL uses Types to reference classes which will later be instantiated. I would like to enforce that a particular Type has been declared within a particular module. This can be a runtime check after the DSL has been compiled.
In essence I need to access the outer element starting from the inner class and check it is of the correct type and get a reference to it.
If I get the child type I can get its symbol using reflection by calling to typeSymbol and in the resulting symbol I see that I can call owner to get the outer type symbol. However if I try to reflect the parent as a Module (even when the parent it is a module) it throws an exception.
Lets put an example:
trait TheMixin
object TheParent extends TheMixin {
case class TheChild()
}
object TestDiscoverParent extends App {
import scala.reflect.runtime.{currentMirror => cm}
val theChildType = typeOf[TheChild]
val theChildOwner = theChildType.typeSymbol.owner
println(theChildOwner)
val theParentModuleSymbol = theChildOwner.asModule
val theParentRef = cm.reflectModule(theParentModuleSymbol).instance
println(theParentRef.isInstanceOf[TheMixin])
}
In this example, the line println(theChildOwner) will print
object TheParent
But the call to theChildOwner.asModule
throws an exception
Exception in thread "main" scala.ScalaReflectionException: object TheParent is not a module
How can I get a reference to the outer object wrapper?
Aucun commentaire:
Enregistrer un commentaire