mjn
mjn

Reputation: 36654

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?

Upvotes: 8

Views: 1633

Answers (1)

Barry Kelly
Barry Kelly

Reputation: 42152

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.

Upvotes: 20

Related Questions