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;
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;
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