How to access private methods without helpers?

前端 未结 6 2080
孤独总比滥情好
孤独总比滥情好 2020-11-28 06:39

In Delphi 10 Seattle I could use the following code to work around overly strict visibility restrictions.

How do I get access to private variables?



        
6条回答
  •  生来不讨喜
    2020-11-28 07:07

    If there is extended RTTI info generated for the class private members - fields and/or methods you can use it to gain access to them.

    Of course, accessing through RTTI is way slower than it was through class helpers.

    Accessing methods:

    var
      Base: TBase2;
      Method: TRttiMethod;
    
      Method := TRttiContext.Create.GetType(TBase2).GetMethod('UsefullButHidden');
      Method.Invoke(Base, []);
    

    Accessing variables:

    var
      Base: TBase;
      v: TValue;
    
      v := TRttiContext.Create.GetType(TBase).GetField('FMemberVar').GetValue(Base);
    

    Default RTTI information generated for RTL/VCL/FMX classes is following

    • Fields - private, protected, public, published
    • Methods - public, published
    • Properties - public, published

    Unfortunately, that means accessing private methods via RTTI for core Delphi libraries is not available. @LU RD's answer covers hack that allows private method access for classes without extended RTTI.

    Working with RTTI

提交回复
热议问题