How to create and attach a custom attribute to a field at runtime in Delphi

Is it possible and how to create and attach a custom attribute to a field at runtime?

uses System.SysUtils, System.Classes, System.Rtti; type MyAttribute = class(TCustomAttribute) private fCaption: string; public constructor Create(const aCaption: string); property Caption: string read fCaption write fCaption; end; TFoo = class(TPersistent) public [MyAttribute('Title')] Bar: string; Other: string; end; constructor MyAttribute.Create(const aCaption: string); begin fCaption := aCaption; end; procedure CreateAttributes(Typ: TRttiType); var Field: TRttiField; MyAttr: MyAttribute; begin for Field in Typ.GetFields do begin if Length(Field.GetAttributes) = 0 then begin MyAttr := MyAttribute.Create('Empty'); // how to attach created attribute to Field ??? end; end; end; var Context: TRttiContext; Typ: TRttiType; Field: TRttiField; Attr: TCustomAttribute; begin Context := TRttiContext.Create; Typ := Context.GetType(TFoo); CreateAttributes(Typ); for Field in Typ.GetFields do for Attr in Field.GetAttributes do if Attr is MyAttribute then writeln(Field.Name + ' ' + MyAttribute(Attr).Caption); readln; Context.Free; end. 

Code execution above:

 Bar Title 

I would like to add MyAttribute to the Empty value in fields that do not have it at runtime, producing the following output:

 Bar Title Other Empty 
+5
source share
2 answers

There is no mechanism in the structure for adding attributes at runtime. Any attempt to do this will result in a hacking framework.

+2
source

Attributes are the magic of compilation time. At runtime, you do not need such things. Just create your own dictionary where the type and member (the member can be set as a string) is the key, and the list of attributes is the value. And when you need to check attributes, do it in two ways - regular and in the dictionary.

0
source

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


All Articles