Search code examples
delphirttitform

RTTI GetFields and GetAttributes on TForm


I have a TForm like this:

TMyForm = class (TForm)
  [MyAttr('Data')] 
  edit1: TEdit;
private
 FData: String;
end

When I try to get the fields of this form via RTTI, I only get the edit1 field, not FDATA, and when I query for edit1 field attributes I get an empty array.

For another class that does not inherit TForm, all works ok. Why?

Edit for sample:

type


{$RTTI EXPLICIT FIELDS([vcPrivate,vcProtected, vcPublic])}
  TForm3 = class(TForm)
    [TCustomAttribute]
    Button1: TButton;
    Memo1: TMemo;
    procedure Button1Click(Sender: TObject);
  private
    { Private declarations }
    [TCustomAttribute]
    FData: String;
  public
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.dfm}

procedure TForm3.Button1Click(Sender: TObject);
var
  LCtx: TRttiContext;
  LField: TRttiField;
  LAttr: TCustomAttribute;
begin
  for LField in LCtx.GetType(Self.ClassInfo).GetDeclaredFields do
  begin
      Memo1.Lines.Add(lField.Name);
      for LAttr in LField.GetAttributes do
        Memo1.Lines.Add(#9+LAttr.ClassName);

  end;
end;

end.

Result where Button1 is clicked:

FData
    TCustomAttribute
Button1
Memo1

Solution

  • There could be a $RTTI directive somewhere in your project that's causing extended RTTI to not work.

    Try adding the following just before the declaration of TMyForm:

    {$RTTI EXPLICIT
      METHODS(DefaultMethodRttiVisibility)
      FIELDS(DefaultFieldRttiVisibility)
      PROPERTIES(DefaultPropertyRttiVisibility)}
    

    This will reset RTTI generation for everything declared after it, and you should get proper RTTI after that point.