且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在没有助手的情况下访问私有方法?

更新时间:2022-11-02 23:14:01

如果有为类私有成员生成的扩展 RTTI 信息 - 字段和/或方法,您可以使用它来访问它们.

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.

当然,通过 RTTI 访问比通过类助手访问要慢得多.

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

访问方法:

var
  Base: TBase2;
  Method: TRttiMethod;

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

访问变量:

var
  Base: TBase;
  v: TValue;

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

为 RTL/VCL/FMX 类生成的默认 RTTI 信息如下


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

  • 字段 - privateprotectedpublicpublished
  • 方法 - public, published
  • 属性 - public, published
  • Fields - private, protected, public, published
  • Methods - public, published
  • Properties - public, published

不幸的是,这意味着无法通过 RTTI 访问核心 Delphi 库的私有方法.@LU RD 的回答 涵盖了允许在没有扩展 RTTI 的情况下访问类的私有方法的技巧.

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.

使用 RTTI