Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delphi Rtti: Explore properties of interfaces?

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?

like image 451
Christian Metzler Avatar asked Sep 12 '10 13:09

Christian Metzler


3 Answers

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.

like image 134
Mason Wheeler Avatar answered Oct 26 '22 18:10

Mason Wheeler


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

like image 43
Baoquan Zuo Avatar answered Oct 26 '22 17:10

Baoquan Zuo


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)
like image 33
FLICKER Avatar answered Oct 26 '22 19:10

FLICKER