Calling a method by name.

Kirk McDonald kirklin.mcdonald at gmail.com
Tue Jun 26 20:29:56 PDT 2007


Lurker #5 wrote:
> One more thing... How can I call a method by name? I was looking at the ClassInfo but I cant' find a way to call a method like this:
> 
> class Commands
> {
>   void command1() {}
>   void command2() {}
>   void command3() {}
> }
> 
> Commands cmds = new Commands();
> char[] cmd = readLine();
> call(cmd, cmd);
> 
> Any ideas on how to implement this call() method?
> 
> Tnks

This is typically a feature seen in dynamic languages like Python or 
Ruby. In D, the names of methods basically just exist at compile-time. 
You'll have to implement the dispatch mechanism yourself, perhaps 
something like:

void call(Commands c, char[] cmd) {
     switch(cmd) {
         case "command1":
             c.command1();
             break;
         case "command2":
             c.command2();
             break;
         case "command3":
             c.command3();
             break;
         default:
             assert(false, "bad command!");
     }
}

-- 
Kirk McDonald
http://kirkmcdonald.blogspot.com
Pyd: Connecting D and Python
http://pyd.dsource.org


More information about the Digitalmars-d-learn mailing list