Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

delphi - How to access private methods without helpers?

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?

type 
  TBase = class(TObject)
  private
    FMemberVar: integer;
  end;

And how do I get access to plain or virtual private methods?

type
  TBase2 = class(TObject) 
  private
    procedure UsefullButHidden;  
    procedure VirtualHidden; virtual;
    procedure PreviouslyProtected; override;
  end;

Previously I would use a class helper to break open the base class.

type
  TBaseHelper = class helper for TBase
    function GetMemberVar: integer;

In Delphi 10.1 Berlin, class helpers no longer have access to private members of the subject class or record.

Is there an alternative way to access private members?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...