How to execute a method (procedure/function) by name

Submitted by:Pitter Alderson

Date added:28 March, 2011

Category:Delphi

Here's a simple trick to execute a Delphi object's method by name:

Tags: execute a delphi object

Code Snippet:

type
TForm1 = class(TForm)
Button1: TButton;
procedure Button1Click(Sender: TObject) ;
procedure CallMeByName(Sender: TObject) ;
private
procedure ExecMethod(OnObject: TObject; MethodName: string) ;
end;

var
Form1: TForm1;

type
TExec = procedure of object;

procedure TForm1.ExecMethod(OnObject: TObject; MethodName: string) ;
var
Routine: TMethod;
Exec: TExec;
begin
Routine.Data := Pointer(OnObject) ;
Routine.Code := OnObject.MethodAddress(MethodName) ;
if NOT Assigned(Routine.Code) then Exit;
Exec := TExec(Routine) ;
Exec;
end;

procedure TForm1.CallMeByName(Sender: TObject) ;
begin
ShowMessage('Hello Delphi!') ;
end;

procedure TForm1.Button1Click(Sender: TObject) ;
begin
ExecMethod(Form1, 'CallMeByName') ;
end;
 
 

Comments