Reflection: Get all inherited classes of a base class

Jonathan M Davis jmdavisProg at gmx.com
Sat Dec 22 14:26:23 PST 2012


On Saturday, December 22, 2012 23:14:28 nrgyzer wrote:
> Hi everyone,
> 
> is it possible to get a list of all inherited classes from a base
> class like this:
> 
> class A {
>     ...
> }
> class B : A {
>     ...
> }
> class C : A {
>     ...
> }
> class D : B {
>     ...
> }
> 
> auto myClasses = __traits(allInheritedClasses, A); // I'm looking
> for something like this.
> assert(myClasses, [B.classinfo, C.classinfo, D.classinfo]);
> 
> All I found wasn't exactly what I need, hence I hope there is any
> chance to do something like that or is there currently no chance?

No, it's not possible. Derived classes don't have to be compiled at the same 
time as the base class. For instance, the base class could be in a library, 
and the derived class could be in a program which is linked against that 
library years after the library was compiled. And if you have shared 
libraries, then more classes could be added to the program months or years 
after the program started if they're loaded while the program is running. 
Granted, you probably won't be running a program for years, but given how D's 
compilation model works, it's something that you can do if your program runs 
long enough, and loading shared libraries after the program has been running 
for a while isn't all that uncommon, even if it's only minutes later rather 
than years (plugins are a good example of that sort of thing).

So, given D's compilation model, it's not even theoretically possible to get a 
list like that, let alone actually possible. Best case, if each class 
registered its existance when it was loaded into the environment (e.g with a 
static constructor), then you could get a list of the classes which are 
currently loaded, but that's not at all what you're asking for here, and you'd 
have to create such a registration mechanism yourself, because no such thing 
is provided by the runtime.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list