I have a class name and a method whose type parameters I know, and I'd like to invoke this method via reflection.
In java I'd do something like:
Class.forName("foo").getMethod("name", ... type args...).invoke(null, ..args)
However in Scala, whenever I try and invoke I get a null ref error.
I'm using scala 2.10.4
-- EDIT
I have tried:
$ scala
Welcome to Scala version 2.10.5 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_102).
Type in expressions to have them evaluated.
Type :help for more information.
scala> class Foo { def bar(x: Int) = x }
defined class Foo
scala> import scala.reflect.runtime.universe._
import scala.reflect.runtime.universe._
scala> val foo = new Foo
foo: Foo = Foo@2db7a79b
scala> runtimeMirror(getClass.getClassLoader).reflect(foo)
res0: reflect.runtime.universe.InstanceMirror = instance mirror for Foo@2db7a79b
scala> res0.symbol.typeSignature.member(newTermName("bar"))
res1: reflect.runtime.universe.Symbol = method bar
scala> res0.reflectMethod(res1.asMethodSymbol)(42)
<console>:15: error: value asMethodSymbol is not a member of reflect.runtime.universe.Symbol
res0.reflectMethod(res1.asMethodSymbol)(42)
^
As an example from "Dynamic" method invocation with new Scala reflection API which doesn't seem to work anymore
Here is a test of what I am trying to do:
object Test{
def run(): Boolean = true
}
class InvokeTests extends FlatSpec with Matchers {
"invoke" should "do" in {
import scala.reflect.runtime.universe._
val mirror = runtimeMirror(this.getClass.getClassLoader)
val moduleSymbol = mirror.moduleSymbol(Class.forName(Test.getClass.getName))
val reflected = mirror.reflect(moduleSymbol)
val methodName = reflected.symbol.typeSignature.member(newTermName("run"))
reflected.reflectMethod(methodName.asMethod)() shouldBe true
}
}