shows how to work with RTTI and attributes
RTTI – Run Time Type Library – is approach that helps to manage code when program is running.
Lets say we have code from someOne without docs. RTTI will help to find methods, invoke them, get / set properties, fields, work with attributes (some meta-information to classes)
defining attributes as derivative from TCustomAttribute
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
SomeAttribute = class(TCustomAttribute) private FText: string; FText2: string; FAge: integer; procedure SetText(const Value: string); procedure SetText2(const Value: string); procedure SetAge(const Value: integer); published constructor Create(AText: string; AText2: string; AAge: integer); property Text: string read FText write SetText; property Text2: string read FText2 write SetText2; property Age: integer read FAge write SetAge; end; |
1 2 3 4 5 6 |
constructor SomeAttribute.Create(AText: string; AText2: string; AAge: integer); begin FText := AText; FTExt2 := AText2; FAge := AAge; end; |
assigning attributes to elements of class
1 2 3 4 5 6 7 8 |
[SomeAttribute('text','text2',123)] TSomeClass = class public [SomeAttribute('text3','text4',1234)] function someProcedure(const s: string): string; [SomeAttribute('text5','text6',12345)] function anotherProcedure(const s: string): string; end; |
reading attributes
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
procedure TMain.bStartClick(Sender: TObject); var ctx: TRttiContext; t: TRttiType; m: TRttiMethod; a: TCustomAttribute; begin Memo.Lines.Clear; ctx := TRttiContext.Create; try t := ctx.GetType(TSomeClass); // for m in t.GetMethods do // if m.Visibility=mvPublic then Memo.Lines.Add(m.Name); for a in m.GetAttributes() do if (a is SomeAttribute) then begin Memo.Lines.Add(Format('Method = %s; Attribute = %s, Text = %s,Text2 = %s Age = %d', [m.Name, a.ClassName, SomeAttribute(a).Text, SomeAttribute(a).Text2, SomeAttribute(a).Age])); end; finally ctx.Free; end; end; |