2.8 dynamic instantiation and invocation

How to instantiate a class and invoke method dynamically?

class Foo {
def index():String = "inside index"
}

I looked on StackOverflow and the suggestion for Scala 2.8 is:

import reflect.Invocation._

val s:String = (new Foo) oo 'index

Seems to work, but I don't know the class ahead of time. I have a substring "Foo" which is parsed from a url string.

Re: 2.8 dynamic instantiation and invocation

You may create Symbols (like 'index) at runtime with Symbol("index")
or any other string.

Of course, the usual caveat emptor for using dynamical method
invocation in a statically typed language applies here as well...

On Wed, Oct 21, 2009 at 4:58 AM, first last wrote:
> How to instantiate a class and invoke method dynamically?
>
> class Foo {
>  def index():String = "inside index"
> }
>
> I looked on StackOverflow and the suggestion for Scala 2.8 is:
>
> import reflect.Invocation._
>
> val s:String = (new Foo) oo 'index
>
> Seems to work, but I don't know the class ahead of time. I have a substring "Foo" which is parsed from a url string.
>
>
>
>

Copyright © 2013 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland