fnkr
fnkr

Reputation: 10095

Delphi How to get default value for property using RTTI

If I have a class like this:

TServerSettings = class(TSettings)
strict private
    FHTTPPort : Integer;
published
    property HTTPPort : Integer read FHTTPPort write FHTTPPort default 80;
end;

How can I get the default attribute of the HTTPPort property using RTTI?

Upvotes: 2

Views: 2102

Answers (2)

David Heffernan
David Heffernan

Reputation: 613612

Like this:

{$APPTYPE CONSOLE}

uses
  System.TypInfo;

type
  TMyClass = class
  strict private
    FMyValue: Integer;
  published
    property MyValue: Integer read FMyValue default 42;
  end;

var
  obj: TMyClass;
  PropInfo: PPropInfo;

begin
  obj := TMyClass.Create;
  PropInfo := GetPropInfo(obj, 'MyValue');
  Writeln(PropInfo.Default);
end.

Note that the class as it stands, just as is so for that in your question, is broken. The system will not automatically initialise properties to their default value when an instance is created. You would need to add a constructor to this class to do that.

Upvotes: 3

RRUZ
RRUZ

Reputation: 136451

You can use the Default property of the TRttiInstanceProperty class

{$APPTYPE CONSOLE}

{$R *.res}

uses
  Rtti,
  System.SysUtils;


type
  TServerSettings = class
  strict private
      FHTTPPort : Integer;
  published
      property HTTPPort : Integer read FHTTPPort write FHTTPPort default 80;
  end;

var
   L : TRttiType;
   P : TRttiProperty;
begin
  try
     P:= TRttiContext.Create.GetType(TServerSettings.ClassInfo).GetProperty('HTTPPort');
     if P is TRttiInstanceProperty  then
       Writeln(TRttiInstanceProperty(P).Default);
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

Upvotes: 4

Related Questions