在Delphi5.0开发人员指南里找到这一段代码:
procedure TMainForm.FormCreate(Sender: TObject);
begin
// Add some example classes to the list box.
lbSampClasses.Items.Add('TApplication');
lbSampClasses.Items.Add('TButton');
lbSampClasses.Items.Add('TForm');
lbSampClasses.Items.Add('TListBox');
lbSampClasses.Items.Add('TPaintBox');
lbSampClasses.Items.Add('TMidasConnection');
lbSampClasses.Items.Add('TFindDialog');
lbSampClasses.Items.Add('TOpenDialog');
lbSampClasses.Items.Add('TTimer');
lbSampClasses.Items.Add('TComponent');
lbSampClasses.Items.Add('TGraphicControl');
end;
procedure TMainForm.lbSampClassesClick(Sender: TObject);
var
SomeComp: TObject;
begin
lbBaseClassInfo.Items.Clear;
lbPropList.Items.Clear;
// Create an instance of the selected class.
SomeComp := CreateAClass(lbSampClasses.Items[lbSampClasses.ItemIndex]);
try
GetBaseClassInfo(SomeComp, lbBaseClassInfo.Items);
GetClassAncestry(SomeComp, lbBaseClassInfo.Items);
GetClassProperties(SomeComp, lbPropList.Items);
finally
SomeComp.Free;
end;
end;
initialization
begin
RegisterClasses([TApplication, TButton, TForm, TListBox, TPaintBox,
TMidasConnection, TFindDialog, TOpenDialog, TTimer, TComponent,
TGraphicControl]);
end;
也就是在MainForm的Create的时候在lbSampleClasses列表框中填入各个类的名字,在运行
时用户选择类名,则动态创建一个控件并获取它的RTTI,应该是通过
function CreateAClass(const AClassName: string): TObject;来实现你要的功能。
需要注意的是,所要动态创建的类必须在Initilization段中注册(见上面的代码)
function CreateAClass(const AClassName: string): TObject;
{ This method illustrates how you can create a class from the class name. Note
that this requires that you register the class using RegisterClasses() as
show in the initialization method of this unit. }
var
C : TFormClass;
SomeObject: TObject;
begin
C := TFormClass(FindClass(AClassName));
SomeObject := C.Create(nil);
Result := SomeObject;
end;