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

0

I am wondering how to get, via RTTIT, 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;
    
asked by anonymous 30.06.2017 / 21:53

1 answer

1

After searching a lot (3 days!) I ended up finding the solution together with a co-worker. The following is an example of the implemented solution within a onClick and a

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;
    
04.07.2017 / 13:32