使用新的Scala反射API调用“动态”方法

时间:2012-06-16 09:12:15

标签: scala reflection

在过去,当Invocation(一个实验性实用程序)是标准库的一部分时,可以“动态”调用方法,如下所示:

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

如何使用新的Scala反射API执行此操作?

1 个答案:

答案 0 :(得分:24)

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

有关如何设计API的一些背景信息,请访问:Get companion object instance with new Scala reflection API