Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
369 views
in Technique[技术] by (71.8m points)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...