【问题标题】:"Dynamic" method invocation with new Scala reflection API使用新的 Scala 反射 API 进行“动态”方法调用
【发布时间】:2012-06-19 04:50:54
【问题描述】:

在过去,当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 做到这一点?

【问题讨论】:

  • 既然已经知道方法的名称/标识符/参数,为什么还要在运行时调用它们?有没有在编译时无法实现的东西?
  • @Antoras,只是好奇。没有真正在生产中使用这些东西。

标签: scala reflection


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-08
    • 1970-01-01
    相关资源
    最近更新 更多