“动态"使用新的 Scala 反射 API 调用方法 [英] "Dynamic" method invocation with new Scala reflection API

查看:37
本文介绍了“动态"使用新的 Scala 反射 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

如何使用新的 Scala 反射 API 做到这一点?

How to do this with the new Scala reflection API?

推荐答案

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 设计方式的一些背景信息:使用新的 Scala 反射 API 获取伴随对象实例.

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

这篇关于“动态"使用新的 Scala 反射 API 调用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆