Skip to content
Delphi

RTTI (Runtime Type Information)

Inspect types and properties at runtime.

By EZ4Code Team
rttireflectionattributes

Code

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;

Explanation

Extended RTTI (since Delphi 2010) enables reflection like C#. Use TRttiContext to inspect types, properties, methods, and attributes. published visibility is required for old-style RTTI; extended RTTI works on public too. Attributes ([…]) attach metadata. RTTI powers serialization, ORM mapping, and DI containers.

More Delphi Snippets