Through rtti, you can also call a class method to read or set its attribute values.
Unit unit1;
Interface
Uses
Windows, messages, sysutils, variants, classes, graphics, controls, forms,
Dialogs, stdctrls;
Type
Tform1 = Class (tform)
Button1: tbutton;
Button2: tbutton;
Procedure button1click (Sender: tobject );
Procedure button2click (Sender: tobject );
End;
{Custom class}
Tmyclass = Class (tcomponent)
Public
Procedure MSG (const STR: string );
Function add (const A, B: integer): integer;
End;
VaR
Form1: tform1;
Implementation
{$ R *. DFM}
Uses rtti;
{Implementation of the myclass class -----------------------------------------------------------}
Procedure tmyclass. MSG (const STR: string );
Begin
Messagedlg (STR, mtinformation, [mbyes], 0 );
End;
Function tmyclass. Add (const A, B: integer): integer;
Begin
Result: = A + B;
End;
// Use the tmyclass method through rtti --------------------------------------
Procedure tform1.button1click (Sender: tobject );
VaR
OBJ: tmyclass;
T: trttitype;
M1, M2: trttimethod;
R: tvalue; // return type of trttimethod. Invoke
Begin
T: = trtticontext. Create. GetType (tmyclass );
{Two methods for obtaining the tmyclass class}
M1: = T. getmethod ('msg '); {procedure}
M2: = T. getmethod ('add'); {function}
OBJ: = tmyclass. Create (Self); {the call must depend on an existing object}
{Call MSG process}
M1.invoke (OBJ, ['delphi 2010 ']); {A message box is displayed}
{Call the Add function}
R: = m2.invoke (OBJ, [1, 2]); {the returned value is a tvalue type structure}
Showmessage (inttostr (R. asinteger); {3}
OBJ. Free;
End;
// Use rtti to modify and obtain attributes of the tmyclass class --------------------------------
Procedure tform1.button2click (Sender: tobject );
VaR
OBJ: tmyclass;
T: trttitype;
P: trttiproperty;
R: tvalue;
Begin
OBJ: = tmyclass. Create (Self );
T: = trtticontext. Create. GetType (tmyclass );
P: = T. getproperty ('name ');
P. setvalue (OBJ, 'newname ');
R: = P. getvalue (OBJ );
Showmessage (R. asstring); {newname}
OBJ. Free;
End;
End.