Convert a class string to TClass [duplicate]
Given the Classes: uses InvokeRegistry; //where TRemotable is defined.
type TMyLabel = class(TRemotable) //some published props TMySubLabel = class(TMyLabel) //more published props //some other classes descendent of TMyLabel.
TMyLabelClass = class of TMyLabel;
My requirement is to implement:
function StringToClass(string aClassName): TClass;
begin
//your implementation goes here
end;
Usage:
function GetMyLabelInstance(string aClassName):TMy开发者_StackOverflowLabel;
var
lCloned: TMyLabel;
begin
Tclass lClass = StringToClass('TMySubLabel');
lCloned := TMyLabelClass(lClass).Create;
end;
I am using Delphi 7 and my objects are not derived from TPersistent, thus this solution is not applicable for my case: How to convert classname as string to a class?
Thanks,
As your classes are not TPersistent
descendants, you have to implement your own RegisterClass
/FindClass
procedures.
I usually do this by registering the classes with their names in a TStringList
(or TDictionary<string, TClass>
for newer Delphi versions), as in TOndrej's answer. I do the registration in the initialization
section of the unit in which the class is defined.
Then you can have a FindClass
function to retrieve the class based on his name, or directly a factory procedure which creates an instance, of the right class based on the name of the class.
I also consider a good practice to pack up the TStringList
, the registration procedure and the factory procedure in one class implemented as a singleton.
If you want to use as a factory you also have to add a virtual constructor to the base class (TMyLabel), and define a metaclass type TMyLabelClass = class of TMyLabel
, and cast the StringList.Objects[i] to TMyLabelClass instead of TClass
精彩评论