How do I create classes dynamically?

Steven Schveighoffer schveiguy at gmail.com
Wed Apr 14 20:47:57 UTC 2021


On 4/14/21 4:38 PM, Mario wrote:
> Maybe I am just too short in D, but I wanted to find out if it is 
> possible to create classes dynamically. My problem is, I just don't know 
> where to start reading. Maybe at mixin templates?
> 
> CreateClassWithName!("MyDynamicClassName");
> 
> should create the following class to work with dynamically:
> 
> class MyDynamicClassName {
>     this() { writeln("I was not written, but still I exist!"); }
> }
> 
> So that I in the end by means of
> 
> MyDynamicClassName cls = new MyDynamicClassName;
> 
> can work with it.
> 
> Normally I would think of a macro first, but as far as I understood D 
> doesn't know macros (which I'm not really sad about), but maybe I'm just 
> thinking too complicated yet. I would appreciate any hints, because as I 
> said, I don't even know where to start reading.
> 

There is no good supported way to do this with the current runtime.

The way this is normally done is to use your own reflection system, and 
build a mechanism to create classes based on their name.

There was an old way, using Object.factory, but I would not recommend 
that, it's brittle and doesn't always work.

-Steve


More information about the Digitalmars-d-learn mailing list