For logging and reporting reasons I create objects that have the class name and message belonging to an Exception. I do this so I don't have to manage the lifetime of the Exception object. What I would like to do is recover the advantages of RTTI identification that allow you to tell if an object is derived from a given class using the "is" operator in Delphi 6.
Is there a way to use a class name in string form to tell if the class the string contains is derived from another class?
Suppose I have the class of an object stored in strClassName and that class is "derivedClass". Further, derivedClass is derived from baseClass. Is there a function I can write that can tell if the class in string form in strClassName is derived from baseClass? For example:
// Hypothetical function that returns TRUE if the class in strClassName is
// derived from the class passed in theBaseClass
function isDerivedClass(strClassName: string; theBaseClass: TAnyClass): boolean;
What would the body of that method look like?
function isDerivedClass(strClassName: string; theBaseClass: TClass): boolean;
begin
Result := FindClass(strClassName).InheritsFrom(theBaseClass);
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
RegisterClass(TLabel); // must be registered to be found by FindClass/GetClass
if isDerivedClass('TLabel', TWinControl) then
..
If you don't want an exception to be raised when a class by the name 'strClassName' cannot be found, use GetClass
instead of FindClass
:
function isDerivedClass(strClassName: string; theBaseClass: TClass): boolean;
var
aClass: TClass;
begin
Result := False;
aClass := GetClass(strClassName);
if Assigned(aClass) then
Result := aClass.InheritsFrom(theBaseClass);
end;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With