Reflection: Get all inherited classes of a base class

nrgyzer nrgyzer at unknownMailAddress.com
Tue Dec 25 10:26:27 PST 2012


On Saturday, 22 December 2012 at 22:28:57 UTC, Adam D. Ruppe 
wrote:
> On Saturday, 22 December 2012 at 22:14:28 UTC, nrgyzer wrote:
>> is it possible to get a list of all inherited classes from a 
>> base class like this:
>
> Yes, though it isn't compile time - gotta be runtime.
>
> ClassInfo[] getChildClasses(ClassInfo c) {
> 	ClassInfo[] info;
>
>         // MoudleInfo is a magical thing in object.d,
>         // implicitly imported, that can loop over all
>         // modules in the program: user and library
> 	foreach(mod; ModuleInfo) {
>                 // the localClasses member gives back
>                 // ClassInfo things that we can compare
> 		foreach(cla; mod.localClasses) {
>                         // note: we could also check this
>                         // recursively and check
>                         // cla.interfaces as well as base
> 			if(cla.base is c)
> 				info ~= cla;
> 		}
> 	}
>
> 	return info;
> }
>
>
> So this should be enough for your example assert, but remember 
> you can't do things like templates on this, since it is all 
> runtime.

Thanks Adam, that's exactly what I need... is it possible to call 
a static method only using TypeInfo_Class or do I need to call 
the constructor using create-method? I think using annotation 
would be very helpful for my idea:

abstract class A {
    static abstract string myName(); // this surely doesn't work
    string[] getChildClassNames() {
       string[] retArray;
       foreach(mod; ModuleInfo) {
          foreach(cla; mod.localClasses) {
             if (cla is this.classinfo)
                retArray ~= cla.myName; // adds "Class B" and 
"Class C"
          }
       return retArray;
    }
}

class B : A {
    override static string myName() { return "Class B"; }
}

class C : A {
    override static string myName() { return "Class C"; }
}

But as in the most other languages it's impossible to declare 
abstract static methods and I also have no direct access from 
TypeInfo_Class to my static attributes and/or methods (or is 
there any chance without creating an instance of the class?).

Hence, annotations would be very useful at this point, but is 
there any other possibility to do something like shown above...?


More information about the Digitalmars-d-learn mailing list