使用RTTI获取单元中定义的类和对象的完整列表

时间:2012-01-25 12:21:07

标签: delphi delphi-xe2 rtti

  1. 我想获得在特定单元中定义的完整类列表
  2. 如何获取这些类的所有实例的列表,无论它们在何处创建?

2 个答案:

答案 0 :(得分:4)

在回答您的问题之前,请记住在与Rtti相关的问题中始终包含您的delphi版本。

1)您正在使用新版本的delphi(> = 2010)的Asumming,您可以使用QualifiedName属性获取类型的单位名称,从那里您必须检查IsInstance属性,以确定是否是一个类。

检查下一个样本。

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Rtti,
  System.SysUtils;

procedure Test;
Var
 t : TRttiType;
  //extract the unit name from the  QualifiedName property
  function GetUnitName(lType: TRttiType): string;
  begin
    Result := StringReplace(lType.QualifiedName, '.' + lType.Name, '',[rfReplaceAll])
  end;

begin
 //list all the types of the System.SysUtils unit
  for t in TRttiContext.Create.GetTypes do
   if SameText('System.SysUtils',GetUnitName(t)) and (t.IsInstance) then
     Writeln(t.Name);
end;

begin
  try
    Test;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

2)Rtti无法列出类的实例。因为Rtti是关于类型信息而不是实例。

答案 1 :(得分:3)

问题1

以下代码根据Delphi 2010中引入的新RTTI做了您的要求:

program FindClassesDeclaredInUnit;

{$APPTYPE CONSOLE}

uses
  SysUtils, Rtti, MyTestUnit in 'MyTestUnit.pas';

procedure ListClassesDeclaredInNamedUnit(const UnitName: string);
var
  Context: TRttiContext;
  t: TRttiType;
  DeclaringUnitName: string;
begin
  Context := TRttiContext.Create;
  for t in Context.GetTypes do
    if t.IsInstance then
    begin
      DeclaringUnitName := t.AsInstance.DeclaringUnitName;
      if SameText(DeclaringUnitName, UnitName) then
        Writeln(t.ToString, ' ', DeclaringUnitName);
    end;
end;

begin
  ListClassesDeclaredInNamedUnit('MyTestUnit');
  Readln;
end.


unit MyTestUnit;

interface

type
  TClass1 = class
  end;

  TClass2 = class
  end;

implementation

procedure StopLinkerStrippingTheseClasses;
begin
  TClass1.Create.Free;
  TClass2.Create.Free;
end;

initialization
  StopLinkerStrippingTheseClasses;

end.

问题2

没有对象实例的全局注册表。