Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
367 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 Reply

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...