Mega Code Archive

 
Categories / Delphi / Examples
 

ReadWrite access to private fields

Title: Read/Write access to private fields Question: How to access pivate fields that do not have property accessors? How to extend classes that do not expose all the properties you need to access? Answer: The preferred way to do it, if possible, is through the technique shown in my previous aticle, but sometimes it is not possible, due to lack of property accessors to the desired field, other times you need speed and RTTI is relatively slow. If you want to access many private properties of the same class, there would be too much code involved on the effort. What to do in this case? Access the private field itsef. In the example below, I will demonstrate how to extend the Delphi streaming system (TReader and TWriter). But as you will notice when loking into the VCL source codes, both classes are higly promiscous, for they access a lot of TFiler's private fields and they are on the same unit. (Private fields can be accessed if the code is on the same unit). There are virtual protected functions that suggest that they are classes designed to be extended, but still you cant access many of the TFiler's properties for they are private and does not have property accessors. The solution is declaring a shadow class on the implementation section of the unit, child of the same parent of TFiler (TObject) with only the private fields, declared in the same order and with the same names. TFilerHack = class(TObject) private FStream: TStream; // other private fields here end Now to use the shadow class to access the FStream field, take a look on the following example: procedure Foo(Filer: TFiler); var Stream: TStream; begin Stream := TFilerHack(Filer).FStream; end ATTENTION: This hack is very sensitive about new versions and changes in the original class, for the fields must be in the same order, having the same types and on the same number in order to be mapped correctly during the type-cast.