I recently found a piece of code that creates an instance of TButton from a string: "TButton" was used as a parameter.
See Is there a way to instantiate a class by name in Delphi?
I am trying to save the published properties of any object in an XML file (which works fine), and recently I want to recreate these objects from an XML file. This file records which class should be created (for example, TButton), and then a list of properties that should be loaded into this object created at run time follows.
The above example shows a way to do this, but it does not work for my class. See the following code:
TTripple=class (TPersistent) FFont:TFont; public constructor Create; Destructor Destroy;override; published property Font:TFont read FFont write FFont; end; var Form1: TForm1; implementation {$R *.dfm} constructor TTripple.Create; begin inherited; FFont:=TFont.Create; end; destructor TTripple.Destroy; begin FFont.Free; inherited; end; procedure TForm1.FormCreate(Sender: TObject); begin RegisterClasses([TButton, TForm, TTripple]); end; procedure TForm1.Button1Click(Sender: TObject); var CRef : TPersistentClass; APer : TPersistent; begin // CRef := GetClass('TButton'); CRef := GetClass('TTripple'); if CRef<>nil then begin APer := TPersistent(TPersistentClass(CRef).Create); ShowMessage(APer.ClassName); // shows TTripple, what is correct if APer is TTripple then (APer as TTripple).Font.Color:=90; /// Here I get error message, because TTriple was not created... ?!?!?! end; end;
I canβt get through. A TTripple object may have been created, but its constructor is not used.
source share