DelphiのRTTI(実行時型情報)を復習する。その2(RTTIユニット)

前回(DelphiのRTTI(実行時型情報)を復習する)の続き。

前回はTypeInfoユニットを使用した。
今回はRTTIユニットを使用する。

■コンポーネントプロパティの型情報を取得する

サンプルプログラム:TButtonの全プロパティを表示する

procedure TForm1.Button1Click(Sender: TObject);
var
  Context: TRttiContext;
  RttiType: TRttiType;
  Properties: TArray<TRttiProperty>;
  RttiProperty: TRttiProperty;
begin
  //RTTI.TRttiContextを作成
  Context := TRttiContext.Create;
  //TButtonの型情報を取得
  RttiType := Context.GetType(TButton);
  //TButtonの全プロパティの配列を取得
  Properties := RttiType.GetProperties;
  //プロパティをListBox1に登録
  for RttiProperty in Properties do
  begin
    ListBox1.Items.Add(RttiProperty.ToString);
  end;
  Context.Free;
end;


全プロパティが表示された。

サンプルプログラム:TButtonの全メソッドを表示する

var
  Context: TRttiContext;
  RttiType: TRttiType;
  RttiMethods: TArray<TRttiMethod>;
  RttiMethod: TRttiMethod;
begin
  Context := TRttiContext.Create;
  RttiType := Context.GetType(TButton);
  RttiMethods := RttiType.GetMethods;
  for RttiMethod in RttiMethods do
  begin
    ListBox1.Items.Add(RttiMethod.ToString);
  end;
  Context.Free;
end;


全メソッドが表示された。

■プロパティの値を取得する

TRttiPropertyのGetValue関数はプロパティの値をTValueで返す。

サンプルプログラム:Button1のCaptionの値を取得する

var
  Context: TRttiContext;
  RttiType: TRttiType;
  RttiProperty: TRttiProperty;
  Caption: String;
begin
  //RTTI.TRttiContextを作成
  Context := TRttiContext.Create;
  //TButtonの型情報を取得
  RttiType := Context.GetType(TButton);
  //TButtonのCaptionプロパティを取得
  RttiProperty := RttiType.GetProperty('Caption');
  //Button1のCaptionプロパティの値を取得
  Caption := RttiProperty.GetValue(Button1).AsString;
  //ListBox1に登録
  ListBox1.Items.Add(Caption);
  Context.Free;
end;


Button1のCaptionプロパティの値がListBoxに表示された。

■プロパティの値を設定する

TRttiPropertyのSetValue関数はプロパティの値を設定する

var
  Context: TRttiContext;
  RttiType: TRttiType;
  RttiProperty: TRttiProperty;
begin
  //RTTI.TRttiContextを作成
  Context := TRttiContext.Create;
  //TButtonの型情報を取得
  RttiType := Context.GetType(TButton);
  //TButtonのCaptionプロパティを取得
  RttiProperty := RttiType.GetProperty('Caption');
  //Button1のCaptionプロパティの値を設定
  RttiProperty.SetValue(Button1, 'ぼたん');
  Context.Free;
end;



ボタンのキャプションが変わった。

■メソッドを実行する

TRttiMethodのInvoke関数はメソッドを呼び出す。

var
  Context: TRttiContext;
  RttiType: TRttiType;
  RttiMethod: TRttiMethod;
begin
  //RTTI.TRttiContextを作成
  Context := TRttiContext.Create;
  //TStringsの型情報を取得
  RttiType := Context.GetType(TStrings);
  //TStringsのAddメソッドを取得
  RttiMethod := RttiType.GetMethod('Add');
  //TStrings.Addを実行
  RttiMethod.Invoke(ListBox1.Items, ['テスト1']);
  RttiMethod.Invoke(ListBox1.Items, ['テスト2']);
  RttiMethod.Invoke(ListBox1.Items, ['テスト3']);

  Context.Free;
end;



ListBoxに追加された。

コメント

  1. Pingback: C++Builder XEでRTTIユニットを使う « 山本隆の開発日誌

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です

このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください