Articles   Members Online:
-Article/Tip Search
-News Group Search over 21 Million news group articles.
Member Area
-Account Center
-Top 10 NEW!!
-Submit Article/Tip
-Forums Upgraded!!
-My Articles
-Edit Information
-Become a Member
-Why sign up!
-Chat Online!
-Indexes NEW!!
-Build your resume
-Find a job
-Post a job
-Resume Search
-Link to us
Visit Embarcadero
Embarcadero Community
How to construct a class instance from a string Turn on/off line numbers in source code. Switch to Orginial background IDE or DSP color Comment or reply to this aritlce/tip for discussion. Bookmark this article to my favorite article(s). Print this article
Delphi 2.x
User Rating
No Votes
# Votes
DSP, Administrator
Reference URL:
			Author: Lou Adler

Is it possible to construct an instance of a class given the name of the class in a 
string variable? I would also want to test that the so named class actually exists 
and is a descendent of another known base class before construction.


Yes, if some preconditions are met. The first thing you need is a class registry, a 
construct that allows you to register all the classes you want to create at 
run-time given the class name. The VCL already contains such a registry for 
TPersistent-derived classes (actually it is used only for TComponent-derived 
classes). Look at RegisterClass, GetClass and FindClass in the online help.

If you have your own hierachry of classes it is quite easy to set up your own class 
registry, using the TClassList class from the Contnrs unit (see online help). You 
would have one instance (a singleton) of TClasslist as your registry, to which you 
add your classes at run-time, typically from the Initialization section of the unit 
that implements the class in question.

Delphi has class reference types (see online help), which are types the values of 
which are classes. So you define such a type for your base class:

1   type
2     TClassAClass = class of TClassA;

TClassA needs to have a virtual constructor (like Tcomponent) for this scheme to 
work properly. You can now derive other classes from TClassA, which may override 
the base classes constructor as appropiate. To find a class in the registry given 
its classname you iterate over the classlist:
4   function CreateInstance(const classname: string; minclass: TClassAClass): TClassA;
5   var
6     i: Integer;
7     classref: TClassAClass
8   begin
9     Result := nil;
10    for i := 0 to classlist.count - 1 do
11    begin
12      classref := TClassAClass(classlist[i]);
13      if classref.ClassnameIs(classname) and classref.InheritsFrom(minclass) then
14      begin
15        Result := classref.Create;
16        Break;
17      end;
18    end;
19  end;

If the constructor needs parameters you have to pass these to your CreateInstance function.

Vote: How useful do you find this Article/Tip?
Bad Excellent
1 2 3 4 5 6 7 8 9 10


Share this page
Download from Google

Copyright © Mendozi Enterprises LLC