Get specific functions of unknown type at runtime?

Adam D. Ruppe destructionator at gmail.com
Sun Dec 16 17:56:32 PST 2012


The way I'd do it is to make an interface with a generic call 
method. The classes themselves fill this out using __traits.


interface SceneObject {
        void _callFunction(string name);
}

mixin template SceneObjectReflection() {
      override void _callFunction(string name) {
            foreach(funcname; __traits(derivedMembers, 
typeof(this))) {
                 static if(funcname[0] != '_') // just to skip 
stuff like _ctor
                 if(funcname == name) {
                     __traits(getMember, this, funcname)();
                     return;
                 }
            }
            throw new Exception("no such method");
      }
}

class Person : SceneObject {
     mixin SceneObjectReflection!();
     void greet() { writeln("hello"); }
}




Then you can use it like:

void main() {
    auto obj = cast(SceneObject) Object.factory("test6.Person") ;
    if(obj is null) throw new Exception("no such class");
    obj._callFunction("greet");
}



Where of course the class name and the function name are runtime 
strings.


It will still be a bumpy ride to make this work in a real world 
situation, but this is how I would get started.


More information about the Digitalmars-d-learn mailing list