Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the list of classes derived from a given class, with enhanced RTTI?

Tags:

delphi

rtti

I need to get a list of form types, but only for types derived from a given base form.

I use Delphi 2010 and enhanced RTTI to browse types

My current code is:

rc := TRTTIContext.Create;
rtyps := rc.GetTypes;
for rtyp in rtyps do
begin
  if not(rtyp.IsInstance) then Continue;

  // Now I need to check if rtyp.AsInstance.MetaclassType is derived from TMyBaseForm
end;

I dont want to instanciate an object and use the 'is' operator, as it would not execute in a timely manner.
As a current workaround, I test if a method, introduced in TMyBaseForm, was found in the RTTI context:

if (rtyp.GetMethod('MyMethod') = nil) then Continue;

but this is not a clean solution, as it can lead to issue if a method with the same name was introduced in another class branch.

So, my question: is there a regular way to detect if a class type is derived from another class type?

Thanks,

like image 537
user315561 Avatar asked Dec 08 '11 16:12

user315561


1 Answers

When you call the AsInstance returns a TRttiInstanceType , from there you must access the MetaclassType property wich is a TClass reference to the reflected type, finally using the TClass you can call the InheritsFrom function

for rtyp in rtyps do
if (rtyp.TypeKind=tkClass) and rtyp.IsInstance and rtyp.AsInstance.MetaclassType.InheritsFrom(TMyBaseForm) then
begin

  // do something
end;
like image 126
RRUZ Avatar answered Nov 02 '22 23:11

RRUZ