Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Dynamic" method invocation with new Scala reflection API

In olden times, when Invocation, an experimental utility, was a part of standard library, one could invoke methods "dynamically" as shown below:

"Hello!" o 'substring(0, 4)  // to get Any back
"Hello!" oo 'substring(0, 4) // for an automatic unsafe cast to expected type

How to do this with the new Scala reflection API?

like image 256
missingfaktor Avatar asked Jun 16 '12 09:06

missingfaktor


1 Answers

Welcome to Scala version 2.10.0-20120617-072418-9a28ee1ffc (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_33).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class Foo { def bar(x: Int) = x }
defined class Foo

scala> val foo = new Foo
foo @ 5935b50c: Foo = Foo@5935b50c

scala> runtimeMirror(getClass.getClassLoader).reflect(foo)
res0 @ 65c24701: reflect.runtime.universe.InstanceMirror = scala.reflect.runtime.JavaMirrors$JavaMirror$JavaInstanceMirror@65c24701

scala> res0.symbol.typeSignature.member(newTermName("bar"))
res1 @ 69624a1c: reflect.runtime.universe.Symbol = method bar

scala> res0.reflectMethod(res1.asMethodSymbol)(42)
res2 @ 4ac1d188: Any = 42

Some background information about how the API is designed can be found here: Get companion object instance with new Scala reflection API.

like image 80
Eugene Burmako Avatar answered Sep 19 '22 18:09

Eugene Burmako