Delphi の interface のプロパティを RTTI で取得
Delphi の interface のプロパティを RTTI で取得
インタフェイスから直接取り出せないため、元のクラスにキャストして取得
キャスト可能なのは Delphi2010以降だそうです
uses System.Rtti;
type
ITest = interface
function GetValue: string;
procedure SetValue(const Value: string);
property Value: string read GetValue write SetValue;
end;
TTest = class(TInterfacedObject, ITest)
private
FValue: string;
function GetValue: string;
procedure SetValue(const Value: string);
public
property Value: string read GetValue write SetValue;
end;
// :::::
procedure TForm1.Button1Click(Sender: TObject);
var
Test: ITest;
TestObj: TTest;
RttiContext: TRttiContext;
RttiType: TRttiType;
RttiProp: TRttiProperty;
begin
Test := TTest.Create;
Test.Value := 'interface rtti';
// 元のクラスにキャスト
TestObj := TTest(Test);
RttiContext := TRttiContext.Create;
try
RttiType := RttiContext.GetType(TestObj.ClassInfo);
for RttiProp in RttiType.GetProperties do begin
Memo1.Lines.Add('Name: ' + RttiProp.Name);
Memo1.Lines.Add('Type: ' + RttiProp.PropertyType.ToString);
if SameText(RttiProp.PropertyType.ToString, 'string') then begin
Memo1.Lines.Add('Value: ' + RttiProp.GetValue(TestObj).AsString);
end
else if SameText(RttiProp.PropertyType.ToString, 'integer') then begin
Memo1.Lines.Add('Value: ' + IntToStr(RttiProp.GetValue(TestObj).AsInteger));
end;
end;
finally
RttiContext.Free;
end;
end;
コメント