Delphi RTTI get the property value of an object that is owned by another

Asked

Viewed 1,245 times

1

I am having doubts about how to obtain, via RTTI, the value of a property of an object that is owned by another. Below are two objects and their relationships. In this example I would like to get the value of S of P1.

TPropriedade = class
strict private
  fS: string;
  fI: Integer;
  procedure SetS(const Value: string);
public
  constructor Create(S: string; I: Integer);
published
  property S: string read fS write SetS;
  property I: Integer read fI;
end;

TObjeto = class
strict private
  fP1: TPropriedade;
  fP2: TPropriedade;
public
  constructor Create;
published
  property P1: TPropriedade read fP1 write fP1;
  property P2: TPropriedade read fP2 write fP2;
end;

implementation

{ TPropriedade }

constructor TPropriedade.Create(S: string; I: Integer);
begin
  fS:= S;
  fI:= I;
end;

procedure TPropriedade.SetS(const Value: string);
begin
  fS:= Value;
end;

{ TObjeto }

constructor TObjeto.Create;
begin
  fP1:= TPropriedade.Create('P1', 1);
  fP2:= TPropriedade.Create('P2', 2);
end;

1 answer

3


After researching a lot (3 days!) I ended up discovering the solution together with a co-worker. Below is an example of the solution implemented within a onClick and a button

procedure TForm1.Button1Click(Sender: TObject);
var
  contexto: TRttiContext;
  TypObj:   TRttiType;
  Prop:     TRttiProperty;
  SubProp:  TRttiProperty;

  obj: TObjeto;
begin
  obj:= TObjeto.Create;

  contexto:= TRttiContext.Create.Create;

  TypObj:= contexto.GetType(obj.ClassInfo);

  Prop:= TypObj.GetProperty('P1');
  SubProp:= Prop.PropertyType.GetProperty('S');

  ShowMessage(SubProp.GetValue(Prop.GetValue(obj).AsObject).ToString);
end;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.