Recently I 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 its name in Delphi?"
I am trying to save published properties of any object to an XML file (which works fine), and lately I want to recreate these objects from the XML file. In this file is written which class is supposed to be created (for example TButton) and then follows a list of properties, which should be loaded into this run-time-created object.
The example above shows the way how to do it, but it does not work for the class of my own. See code below:
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 not get through. The TTripple object is perhaps created, but its constructor is not used.