Retrieving the entire list of classes and objects defined in the module using RTTI

  • I want to get the whole list of classes defined in a specific module
  • How can I get a list of all instances of these classes, regardless of where they are created?
+4
source share
2 answers

Before answering your question, remember that always include the delphi version in questions related to Rtti.

1) When using the new version of delphi (> = 2010) you can get the name of the unit of type using QualifiedName , from there you should check the IsInstance property to determine if the class is.

Check out the following sample.

 {$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 cannot list instances of classes. because Rtti is type information, not instances.

+4
source

Question 1

The following code does what you ask, building on the new RTTI introduced in Delphi 2010:

 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. 

Question 2

There is no global registry of object instances.

+3
source

Source: https://habr.com/ru/post/1392921/


All Articles