Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a protected method (constructor) via RTTI

am using XE-2.

Is it possible to invoke a protected method (constructor) using RTTI?

I searched the web but did not find any conclusive answer. I understand that prior to XE only published methods/properties were available. I do have write access to private fields, so I was expecting to be able to invoke protected methods.

The following code works as long as the constructor is public.

function GetDefaultConstructor(aRttiType: TRttiType): TRttiMethod;
var
   Method: TRttiMethod;
begin
   for Method in aRttiType.GetMethods('Create') do
   begin
      if (Method.IsConstructor) and (length(Method.GetParameters) = 0) and (Method.Parent = aRttiType) then
         Exit(Method);
   end;
   Result := nil;
end;
like image 829
santiagoIT Avatar asked Apr 14 '15 17:04

santiagoIT


1 Answers

By the default the RTTI doesn't include info about the protected methods or constructors, However you can use RTTI EXPLICIT Directive to include RTTI info of protected methods like so.

  {$RTTI EXPLICIT METHODS([vcPrivate, vcProtected, vcPublic, vcPublished])}
  TFoo= class
  protected
    constructor Create;
  end;
like image 169
RRUZ Avatar answered Oct 18 '22 02:10

RRUZ