Thursday, November 11, 2010

scalaでstructural typingでreflection

Scala: How do I dynamically instantiate an object and invoke a method using reflection?

にstructural typingを使ったサンプルが載ってたのでメモ

  1. class Foo {  
  2.   def hello(name: String): String = "Hello there, %s".format(name)  
  3. }  
  4.   
  5. object FooMain {  
  6.   
  7.   def main(args: Array[String]) {  
  8.     val foo  = Class.forName("Foo").newInstance.asInstanceOf[{ def hello(name: String): String }]  
  9.     println(foo.hello("Walter")) // prints "Hello there, Walter"  
  10.   }  
  11. }  

No comments:

Post a Comment