2012-06-16 73 views
17

古時,當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來做到這一點?

+0

爲什麼你想在運行時調用方法,當你已經知道他們的名字/標識符/參數?有什麼你在編譯時無法實現的嗎? – sschaef

+0

@Antoras,只有好奇。不是真的在生產中使用這些東西。 – missingfaktor

回答

22
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 = [email protected] 

scala> runtimeMirror(getClass.getClassLoader).reflect(foo) 
res0 @ 65c24701: reflect.runtime.universe.InstanceMirror = [email protected]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