Skip to content
Delphi

RTTI (Informação de Tipo em Tempo de Execução)

Inspecionar tipos e propriedades em tempo de execução.

#rtti#reflection#attributes

Code

delphi
uses
  System.Rtti, System.TypInfo;

type
  [DisplayName('My Widget')]
  TWidget = class
  private
    FName: string;
    FPrice: Double;
  published
    property Name: string read FName write FName;
    property Price: Double read FPrice write FPrice;
  end;

// Get type info
var
  ctx: TRttiContext;
  t: TRttiType;
  attr: TCustomAttribute;
  p: TRttiProperty;
begin
  ctx := TRttiContext.Create;
  try
    t := ctx.GetType(TWidget);

    // Read attribute
    for attr in t.GetAttributes do
      if attr is DisplayNameAttribute then
        ShowMessage((attr as DisplayNameAttribute).Name);

    // Enumerate properties
    for p in t.GetProperties do
      ShowMessage(p.Name + ': ' + p.PropertyType.Name);

    // Get/Set property value on instance
    var W := TWidget.Create;
    try
      p := t.GetProperty('Name');
      p.SetValue(W, 'Gadget');
      ShowMessage(p.GetValue(W).AsString);
    finally
      W.Free;
    end;
  finally
    ctx.Free;
  end;
end;