Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi: At runtime find classes that descend from a given base class?

Is there at way, at runtime, to find all classes that descend from a particular base class?

For example, pretend there is a class:

TLocalization = class(TObject)
...
public
   function GetLanguageName: string;
end;

or pretend there is a class:

TTestCase = class(TObject)
...
public
   procedure Run; virtual;
end;

or pretend there is a class:

TPlugIn = class(TObject)
...
public
   procedure Execute; virtual;
end;

or pretend there is a class:

TTheClassImInterestedIn = class(TObject)
...
public
   procedure Something;
end;

At runtime i want to find all classes that descend from TTestCase so that i may do stuff with them.

Can the RTTI be queried for such information?

Alternatively: Is there a way in Delphi to walk every class? i can then simply call:

RunClass: TClass;

if (RunClass is TTestCase) then
begin
   TTestCase(RunClass).Something;
end;

See also

  • Finding all classes that derive from a given base class in python
  • Java: At runtime, find all classes in app that extend a base class
like image 718
Ian Boyd Avatar asked Sep 26 '10 02:09

Ian Boyd


1 Answers

It can be done with RTTI, but not in Delphi 5. In order to find all classes that match a certain criteria, you first need to be able to find all classes, and the RTTI APIs necessary to do that were introduced in Delphi 2010. You'd do it something like this:

function FindAllDescendantsOf(basetype: TClass): TList<TClass>;
var
  ctx: TRttiContext;
  lType: TRttiType;
begin
  result := TList<TClass>.Create;
  ctx := TRttiContext.Create;
  for lType in ctx.GetTypes do
    if (lType is TRttiInstanceType) and
       (TRttiInstanceType(lType).MetaclassType.InheritsFrom(basetype)) then
      result.add(TRttiInstanceType(lType).MetaclassType);
end;
like image 165
Mason Wheeler Avatar answered Oct 30 '22 07:10

Mason Wheeler