RTTI Tutorial

From RAD Studio
Jump to: navigation, search


Go Up to Run-Time Type Identification(RTTI)

Step 1: Creating the Project

1. Create a new project. Choose a Multi-Device Application for this example. In the wizard, choose Blank Application.
2. Select the form and change the Caption property in the Object Inspector to "RTTI Sample".
3. Select the TListBox component in the Tool Palette, and drop it on the Form Designer.
4. Add a TButton component to the form, and change the Name property to ButtonFill and the Text property to Fill.

Step 2: Fill the ListBox at Runtime

This example shows how to obtain the ancestry of a component using the ClassType and ClassParent properties. It uses a TButton and a TListBox component on a form. When the user clicks the button, the name of the button’s class and the names of its parent classes are added to the list box.

To add the OnClick event handler

1. On the form, select ButtonFill component.
2. In the Object Inspector, open the Events tab, an then double-click OnClick.
3. In the Code Editor, add the following code:

Delphi:

procedure TForm1.ButtonFillClick(Sender: TObject);
var
   ClassRef: TClass;
begin
   ListBox1.Clear;
   ClassRef := Sender.ClassType;

   while ClassRef <> nil do
   begin
     ListBox1.Items.Add(ClassRef.ClassName) ;
     ClassRef := ClassRef.ClassParent;
   end;

end;

C++:

void __fastcall TForm1::ButtonFillClick(TObject *Sender)
{
   TClass ClassRef;

   ListBox1->Clear();
   ClassRef = Sender->ClassType();

   while (ClassRef != NULL)
   {
	ListBox1->Items->Add(ClassRef->ClassName());
	ClassRef = ClassRef->ClassParent();
   }
}

The Results

To run the application, press F9 or choose Run > Run.

See Also