Get class instance by class name string

Posted by VDVLeon on Stack Overflow See other posts from Stack Overflow or by VDVLeon
Published on 2010-05-28T16:07:04Z Indexed on 2010/05/28 16:12 UTC
Read the original article Hit count: 145

Hi all,

I noticed the function Object.factory(char[] className) in D. But it does not work like I hoped it would work; it does not work ;)

An example:

import std.stdio;

class TestClass
{
    override string toString()
    {
        return typeof(this).stringof; // TestClass
    }
};

void main(string[] args)
{
    auto i = Object.factory("TestClass");
    if (i is null)
    {
        writeln("Class not found");
    }
    else
    {
        writeln("Class string: " ~ i);
    }
}

I think this should result in the message: "Class string: TestClass" but it says "Class not found".

Does anybody know why this happens and how I could fix it ?

Or do I need to make my own class factory. For example by make a class with a static array Object[string] classes; with class instances. When I want a new instance I do this:

auto i = (className in classes);
if (i is null)
{
    return null;
}
return i.classinfo.create();

© Stack Overflow or respective owner

Related posts about object-oriented

Related posts about d