lundi 18 avril 2016

Can I get an instance of outer class using reflection on inner class type?

I'm trying to use scala reflection to achieve this:

val labelBar = Named("bar")
val labelFoo = NamedFunc("foo", (i: Int) => println(i))

val i = newInstance[
    labelBar.Var[Int] +
    labelFoo.Func[Int => Unit]
  ]

i.foo(2)
i.bar = 20

It uses a newInstace method to create a new object with specified members. To allow dynamic members, I use the scala's Dynamic class.
newInstance takes an implicit TypeTag argument. Var is an inner classes for the Named class:

case class Named(name: String) {
  outer =>
  class asVar[T]() {
    def getOuter: Named = outer
  }
}

class +[A, B]

My problem is that I can't use reflectClass on Type representing inner class. It throws this:

scala.ScalaReflectionException: class asVar is an inner class, use reflectClass on an InstanceMirror to obtain its ClassMirror
at scala.reflect.runtime.JavaMirrors$JavaMirror.scala$reflect$runtime$JavaMirrors$JavaMirror$$abort(JavaMirrors.scala:115)
at scala.reflect.runtime.JavaMirrors$JavaMirror.ErrorInnerClass(JavaMirrors.scala:117)
at scala.reflect.runtime.JavaMirrors$JavaMirror.reflectClass(JavaMirrors.scala:183)

Is there a way to get around it? Does Scala even hold this instance?





Aucun commentaire:

Enregistrer un commentaire