2009年8月28日金曜日

Rttiを試して見る

動的にメソッドを読み出す簡単なプログラムを作ってみました。
プログラムそのものには意味はありません。

プレビュー会に説明があったようにprivateなメソッドは読めませんでした。
メソッドの可視属性を示す型があったので読めてもよいと思ったのですが・・・

また、GetDeclaredMethodsをつかうと自分が宣言したメソッドのみ
リストできます。

以下ソースです。

  1. unit Unit1;  
  2.   
  3. interface  
  4.   
  5. uses  
  6.  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,  
  7.  Dialogs, StdCtrls, ExtCtrls;  
  8.   
  9. type  
  10.  TForm1 = class(TForm)  
  11.    Button1: TButton;  
  12.    LabeledEdit1: TLabeledEdit;  
  13.    Button2: TButton;  
  14.    ListBox1: TListBox;  
  15.    procedure Button1Click(Sender: TObject);  
  16.    procedure Button2Click(Sender: TObject);  
  17.  private  
  18.    { Private 宣言 }  
  19.    //procedure SakaTest2;  
  20.  protected  
  21.    //procedure SakaTest1;  
  22.    procedure SakaTest2;  
  23.  public  
  24.    { Public 宣言 }  
  25.    procedure SakaTest2;  
  26.    procedure SakaTest1;  
  27.  end;  
  28.   
  29. var  
  30.  Form1: TForm1;  
  31.   
  32. implementation  
  33. uses  
  34.  Rtti,TypInfo;  
  35.   
  36. {$R *.dfm}  
  37.   
  38. procedure TForm1.Button1Click(Sender: TObject);  
  39. var  
  40.  ctx : TRttiContext;  
  41.  rtm : Rtti.TRttiMethod;  
  42.  obj : TObject;  
  43.  Args : Array of TValue;  
  44. begin  
  45.  //  
  46.  ctx := TRttiContext.Create;  
  47.   
  48.   
  49.  //rtm := ctx.GetType(obj).GetMethod(LabeledEdit1.Text);  
  50.   
  51.  rtm := ctx.GetType(Self.ClassType).GetMethod(LabeledEdit1.Text);  
  52.   
  53.  if rtm <> nil then  
  54.  begin  
  55.    //obj := Self;  
  56.    rtm.Invoke(Self,Args);  
  57.  end;  
  58.   
  59. end;  
  60.   
  61. procedure TForm1.Button2Click(Sender: TObject);  
  62. var  
  63.  ctx : TRttiContext;  
  64.  rtmary : TArray<rtti.trttimethod>;  
  65.  rtm : TRttiMethod;  
  66.  obj : TObject;  
  67.  Args : Array of TValue;  
  68.  rtp : TRttiType;  
  69. begin  
  70.   
  71.  ctx := TRttiContext.Create;  
  72.   
  73.  //rtm := ctx.GetType(obj).GetMethod(LabeledEdit1.Text);  
  74.  //ctx.FindType()  
  75.  //rtp := ctx.GetType(Self.ClassType);  
  76.  //rtp.IsPublicType := false;  
  77.   
  78.  rtmary := ctx.GetType(Self.ClassType).GetDeclaredMethods;  
  79.   
  80.  ListBox1.Clear;  
  81.   
  82.  if rtmary <> nil then  
  83.  begin  
  84.    for rtm in rtmary do  
  85.    begin  
  86.      ListBox1.Items.Add(rtm.Name);  
  87.      if rtm.Name = LabeledEdit1.Text then  
  88.      begin  
  89.        rtm.Invoke(Self,Args);  
  90.      end;  
  91.   
  92.    end;  
  93.   
  94.  end;  
  95.   
  96. end;  
  97.   
  98. procedure TForm1.SakaTest1;  
  99. begin  
  100.  Application.MessageBox('Hello Delphi','First Text');  
  101. end;  
  102.   
  103. procedure TForm1.SakaTest2;  
  104. begin  
  105.  Application.MessageBox('Hello Delphi','Second Text');  
  106. end;  
  107.   
  108. end.  
  109. </rtti.trttimethod>  


引数つきのメソッドコールはまた次回

0 件のコメント: