Getting derived classes

Christopher Wright dhasenan at gmail.com
Sat Nov 1 07:37:06 PDT 2008


Steven Schveighoffer wrote:
> "Sean Kelly" wrote
>> Andrei Alexandrescu wrote:
>>> Anyhow, there's a start with the function static Object.factory(string).
>>> You give it a string, it gives you a newly-instanced object. So the
>>> information is there, it just needs exposing.
>> Much of it is even exposed, just not in a convenient manner.  A list of 
>> classes is available via ModuleInfo, and ClassInfo provides a means of 
>> finding the ClassInfo instance of a class by name.  From there it should 
>> be possible to obtain a list of parent classes, and so one could build a 
>> hierarchy graph with some work.
> 
> Sure, but what do you do with that graph ;)  Calling methods/ctors is not 
> exactly easy with D currently.
> 
> -Steve 

Parameterless constructors are easy. Other than that, you can't be 
certain what expectations the constructor has, so it's a bit dangerous, 
but you can of course get around that with documentation and try/catch.

Calling methods isn't so difficult, either, since most of the stuff 
you'll be able to do involves virtual methods from some known base class.

Dunit uses runtime reflection to get all test fixtures and run them. It 
uses something like:
ClassInfo[] derived(ClassInfo info)
{
	ClassInfo[] derivedClasses;
	foreach (module; ModuleInfo) foreach (clazz; module.localClasses)
	{
		if (isDerived(clazz; info)) derivedClasses ~= clazz;
	}
	return derivedClasses;
}

// Only works for interfaces.
bool isDerived(ClassInfo derived, ClassInfo base)
{
	while (derived)
	{
		if (base is derived) return true;
		derived = derived.base;
	}
}

I did this because I was tired of the static ctor mixin / static 
singleton registration pattern. I used to have to do:
class FooTests : TestFixture
{
	// I already told you it's a test fixture!
	// You mean I have to tell you twice?!
	mixin (DunitTest);
}

Now I can skip the mixin.



More information about the Digitalmars-d mailing list