Accesing a strict private field using the RTTI

五迷三道 提交于 2019-11-30 14:50:54

I can't try it right now, but what you seem to need could be GetDeclaredFields instead of GetFields. This should give all (instance) fields of a class but not those of an ancestor class. If you need those too, you'll have to recursively go up the inheritance chain.

As I said, I can't try it right now, so you'll have to see for yourself if it gives you access to strict private fields as well.

Update

Note that in your declaration of TFoo, even you probably didn't intend it, both Field1 and Field2 are class variables!.

Just reformat your declaration, and you'll see what I mean:

  TFoo = class
  strict private
    class var
      Field1: Integer;
      Field2: Integer;
  private
    // etc...

Everything that comes after class var is a class variable, until the compiler encounters var, strict, private, protected, etc. Try this, and you'll also see Field2 being written:

  TFoo = class
  strict private
    class var 
      Field1: Integer;
    var 
      Field2: Integer;
    // etc...

Alternatively try:

  TFoo = class
  strict private
    Field2: Integer;
    class var 
      Field1: Integer;
    // etc...

This means that GetFields and GetDeclaredFields don't have any problems with strict private fields. They just don't return class variables. That makes sense, IMO. Class variables are not members of the object being investigated.

LU RD

Access to strict private members of a class is possible with Class Helpers.

See access-a-strict-protected-property-of-a-delphi-class for a working example.

Related is also how-can-access-the-value-of-a-class-var-using-the-address-of-the-class-and-a-offset-to-the-variable, where class helpers is used to access a strict private class var.

By definition, strict private is only visible in the scope of the class itself. They should still be accessible with Hallvard's hack #5, though (except for class fields, I think).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!