Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Is it possible and how to create and attach custom attribute to 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.

Running above code produces output:

Bar Title

I would like to inject MyAttribute with value Empty to fields that don't have it at runtime producing following output:

Bar Title
Other Empty
like image 884
Dalija Prasnikar Avatar asked Mar 28 '15 12:03

Dalija Prasnikar


1 Answers

The framework provides no mechanism for attaching attributes at runtime. Any attempt to do so would involve hacking the framework.

like image 84
David Heffernan Avatar answered Oct 05 '22 23:10

David Heffernan