2012-06-16 9 views
17

と「ダイナミック」メソッド呼び出し、:新しいScalaのリフレクションAPI

どう
"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です。

関連する問題