Calling a method by name.

Derek Parnell derek at nomail.afraid.org
Tue Jun 26 20:46:44 PDT 2007


On Tue, 26 Jun 2007 22:28:31 -0400, 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);

The names of the methods and functions are 'lost' during the compilation
process, so you might like to set up your own name to function mapping.

Something like this I find useful...

// --------------------
import std.stdio;

// Here are the definition of the known commands.
void command1()
{
   writefln("Cmd #1");
}

void command2()
{
   writefln("Cmd #2");
}

void command3()
{
   writefln("Cmd #3");
}

void function()[string] RMap; // List of commands, mapped by name.

// Call a command.
void call(string cmdname)
{
    if (cmdname in RMap)
    {
        writef("Calling '%s': ", cmdname);
        RMap[cmdname]();
    }
    else
    {
        throw new Exception("'" ~ cmdname ~ "' is not mapped to a
command.");
    }
}

// Initialize the Name -> Command mapping
static this()
{
    RMap["One"]     = &command1;
    RMap["Two"]     = &command2;
    RMap["Three"]   = &command3;
}

void main()
{

    // Invoke some commands to test it.
    call("Two");
    call("One");
    call("One");
    call("Three");
    call("Four"); // Should fail 'cos not mapped

}
// ---------------

-- 
Derek
(skype: derek.j.parnell)
Melbourne, Australia
27/06/2007 1:40:20 PM


More information about the Digitalmars-d-learn mailing list