9
votes

Is there a way to explore a interface's properties with Rtti?

The following code does not work:

procedure ExploreProps;
var
  Ctx: TRttiContext;
  RttiType: TRttiType;
  RttiProp: TRttiProp;
begin
  RttiType := Ctx.GetType(TypeInfo(IMyInterface));
  for RttiProp in RttiType.GetProperties do
    Writeln(RttiProp.ToString);
end;

Has anyone a solution how to do this correctly?

4

4 Answers

5
votes

Interfaces are collections of functions. They don't really have properties the way objects do; that's just a bit of syntactic sugar that the compiler adds for you to make it easier to write code for them. The difference is that on objects, properties allow controlled access to private and protected members, whereas on interfaces, all members are public so there's no need for the properties.

1
votes

As I known, there is no support for normal interfaces. You could add {$M+} and then try again.

1
votes

Add this function in your interface

function GetObject: TObject;

and implement it in the class. the use the GetObject function with RTTI routines

var
  obj: IPerson;
begin
  obj := TPerson.Create;
  Count := GetPropList(obj.GetObject.ClassInfo, tkAny, @List);
end;

Please note that your class should be inherited from TInterfacedPersistent not TInterfacedObject

TPerson = class(TInterfacedPersistent, IPerson)
-1
votes

late answer, but you could typecast your interfae to TObject, e.g.

RttiType := Ctx.GetType(TObject(IMyInterface).ClassInfo);