Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enumerate all Delphi classes that implement a given interface?

With the new extended RTTI in Delphi 2010, can a Delphi application (at run time) build a list of all classes which implement a given interface?

like image 521
mjn Avatar asked Feb 06 '10 21:02

mjn


1 Answers

Technically yes, so long as the interface has a GUID and the classes you care about are in the interface sections of units.

The RTTI unit does not (yet) have an API for describing all interfaces that a class implements, but the data is in the type info.

The GUID for an interface type can be gotten from this expression:

GetTypeData(TypeInfo(ITheInterface))^.Guid

or:

ctx: TRttiContext;
// ...
(ctx.GetType(TypeInfo(ITheInterface)) as TRttiInterfaceType).GUID

The class of the instance type can then be checked using TClass.GetInterfaceEntry(IID) - if it returns non-nil, the class implements the interface.

All classes declared in interface sections of units can be retrieved via TRttiContext.GetTypes.

Writing the actual iteration and extraction code is left as an exercise for the reader.

like image 64
Barry Kelly Avatar answered Nov 06 '22 09:11

Barry Kelly