mercredi 5 octobre 2016

Get a MethodMirror for a method on a package object

I need to use reflection to call a method that is defined on a package object.

package com.coryklein

package object kittens {
  def purr = "meow"
}

The Mirrors documentation says:

Scala only has instance methods-- methods of objects are instance methods of object instances, obtainable via ModuleMirror.instance

There is even a generous example of using reflection to call a method x on a defined class C.

scala> class C { def x = 2 }
defined class C

scala> val im = m.reflect(new C)
im: reflect.runtime.universe.InstanceMirror = instance mirror for C@3442299e

scala> val methodX = typeOf[C].declaration(TermName("x")).asMethod
methodX: reflect.runtime.universe.MethodSymbol = method x

scala> val mm = im.reflectMethod(methodX)
mm: reflect.runtime.universe.MethodMirror = method mirror for C.x: scala.Int (bound to C@3442299e)

scala> mm()
res0: Any = 2

It seems that from here it shouldn't be too difficult to adapt the approach to reflecting a method that exists on an package object. However, a package object doesn't have a corresponding class to obtain the method from via reflection.

I have been able to obtain the method symbol:

mirror.staticPackage("com.coryklein.kittens").info.decls
  .find(_.name.decodedName.toString == "purr").get

But at this point, I don't have an instance mirror equivalent to im from above to reflect this method.

How would I call the purr method defined in package object kittens via Scala reflection?





Aucun commentaire:

Enregistrer un commentaire