user315561
user315561

Reputation: 671

How to get the list of classes derived from a given class, with enhanced 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,

Upvotes: 13

Views: 2078

Answers (1)

RRUZ
RRUZ

Reputation: 136391

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;

Upvotes: 13

Related Questions