1. Technology

Using RTTI in Delphi

Runtime Type Information Unleashed


Delphi provided Runtime Type Information (RTTI) more than a decade ago. Yet even today many developers aren't fully aware of its risks and benefits. This article provides an overview of the RTTI usage in Delphi for Win32.

In short, Runtime Type Information is information about an object's data type that is set into memory at run-time.
You are probably using this powerful but unfortunately inadequately documented feature of Delphi in your every day projects.

RTTI provides a way to determine if an object's type is that of a particular class or one of its descendants. The is and as operators commonly used in Delphi language, rely on the presence of some form of RTTI. The is operator, which performs dynamic type checking, is used to verify the actual runtime class of an object. The as operator performs checked typecasts.
In Delphi 7 (and 2005) the typinfo unit defines type, classes and objects you use when working with the RTTI.

RTTI in Delphi - Explained

The "Run-Time Type Information In Delphi - Can It Do Anything For You?" article by Brian Long provides a great introduction to the RTTI capabilities of Delphi. Brian explains that the RTTI support in Delphi has been added first and foremost to allow the design-time environment to do its job, but that developers can also take advantage of it to achieve certain code simplifications.

This article also provides a great overview of the RTTI classes along with a few examples. Examples include: Reading and writing arbitrary properties, common properties with no common ancestor, copying properties from one component to another, etc.

RTTI in Delphi - An Example

Here's a small example of the powers of the RTTI. This example shows how to obtain the ancestry of a component using the ClassType and ClassParent properties. It uses a button and a list box 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 (found in the Delphi Help).

procedure TForm1.Button1Click(Sender: TObject) ;

   ClassRef: TClass;
   ClassRef := Sender.ClassType;
   while ClassRef <> nil do
     ListBox1.Items.Add(ClassRef.ClassName) ;
     ClassRef := ClassRef.ClassParent;

The list box contains the following strings after the user clicks the button:


RTTI in Delphi - More Examples

Using And Understanding New RTTI in Delphi >= 2010

Support for RTTI in Delphi had a facelift (and that some) in Delphi 2010. Go for Using And Understanding New RTTI in Delphi >= 2010 RTTI is really great. You can use it in many different ways to those provided here. I hope you'll find plenty other ways to exploit this remarkably under-used feature of Delphi.
Related Video
Using Meta Data for Search

©2014 About.com. All rights reserved.