Overview

RTTI

Inspecting types at runtime via Attributes

Source Code

<?pas
// RTTI: Inspecting types at runtime via Attributes

type
  TStatus = (Active, Inactive, Pending);

type
  TUser = class
  private
    FId: Integer;
  published
    Name: String;
    Email: String;
    Status: TStatus;
    
    procedure Activate;
    begin
      Status := Active;
    end;
    
    function IsActive: Boolean;
    begin
      Result := Status = Active;
    end;
  end;

var typeID := TypeOf(TUser);
PrintLn('=== Type Info for ' + TUser.ClassName + ' ===');
PrintLn('');

// In DWScript, published members are exposed via the RTTI attributes system
var rtti := RTTIRawAttributes;

PrintLn('Published Fields/Properties:');
for var i := 0 to rtti.Length - 1 do begin
  var attr := rtti[i];
  if (attr.T = typeID) and (attr.A is RTTIPropertyAttribute) then begin
     var prop := RTTIPropertyAttribute(attr.A);
     PrintLn('  ' + prop.Name + ': ' + prop.Typ.Name);
  end;
end;
PrintLn('');

PrintLn('Methods:');
for var i := 0 to rtti.Length - 1 do begin
  var attr := rtti[i];
  if (attr.T = typeID) and (attr.A is RTTIMethodAttribute) then begin
     var meth := RTTIMethodAttribute(attr.A);
     var kind := if meth.Typ.Name <> '' then 'function' else 'procedure';
     PrintLn('  ' + kind + ' ' + meth.Name);
  end;
end;
PrintLn('');

// Dynamic interaction
var user := TUser.Create;
user.Name := 'Alice';

// Find and use property dynamically
for var i := 0 to rtti.Length - 1 do begin
  var attr := rtti[i];
  if (attr.T = typeID) and (attr.A is RTTIPropertyAttribute) then begin
     var prop := RTTIPropertyAttribute(attr.A);
     if prop.Name = 'Name' then
        PrintLn('Dynamic Name access: ' + VarToStr(prop.Getter(user)));
  end;
end;
?>

Result

=== Type Info for TUser ===

Published Fields/Properties:
  Email: String
  Name: String
  Status: TStatus

Methods:
  procedure Activate
  function IsActive

Dynamic Name access: Alice
On this page