8

I want to create a form given its class name as a string, which has been asked about before, but instead of calling GetClass, I want to use Delphi's new RTTI feature.

With this code, I've got a TRttiType, but I don't know how to instantiate it.

var
  f:TFormBase;
  ctx:TRttiContext;
  lType:TRttiType;
begin
  ctx := TRttiContext.Create;
  for lType in ctx.GetTypes do
  begin
    if lType.Name = 'TFormFormulirPendaftaran' then
    begin
      //how to instantiate lType here?
      Break;
    end;
  end;
end;

I've also tried lType.NewInstance with no luck.

Community
  • 1
  • 1
Niyoko
  • 7,512
  • 4
  • 32
  • 59

2 Answers2

11

You must cast the TRttiType to the TRttiInstanceType class and then invoke the constructor using the GetMethod function.

Try this sample

var
  ctx:TRttiContext;
  lType:TRttiType;
  t : TRttiInstanceType;
  f : TValue;
begin
  ctx := TRttiContext.Create;
  lType:= ctx.FindType('UnitName.TFormFormulirPendaftaran');
  if lType<>nil then
  begin
    t:=lType.AsInstance;
    f:= t.GetMethod('Create').Invoke(t.MetaclassType,[nil]);
    t.GetMethod('Show').Invoke(f,[]);
  end;
end;
RRUZ
  • 134,889
  • 20
  • 356
  • 483
  • Once you have instantiated the Form object, you don't need to use RTTI anymore to call its `Show()` method. Just call it normally: `f.Show;` – Remy Lebeau Feb 07 '13 at 03:03
  • @RemyLebeau, on this sample f is a TValue, off course the OP can introduce a TForm helper variable or just cast the TValue to a Tform like so `TForm(f.AsObject).Show;` – RRUZ Feb 07 '13 at 03:10
  • Sorry, I didn't notice that `f` was a `TValue`, I was looking at Niyoko's code when I saw that. – Remy Lebeau Feb 07 '13 at 03:51
4

You should use the TRttiContext.FindType() method instead of manually looping through though the TRttiContext.GetTypes() list, eg:

lType := ctx.FindType('ScopeName.UnitName.TFormFormulirPendaftaran');
if lType <> nil then
begin
  ...
end;

But either way, once you have located the TRttiType for the desired class type, you can instantiate it like this:

type
  TFormBaseClass = class of TFormBase;

f := TFormBaseClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere);

Or this, if TFormBase is derived from TForm:

f := TFormClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere);

Or this, if TFormBase is derived from TCustomForm:

f := TCustomFormClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere);

Update: Or, do it like @RRUZ showed. That is more TRttiType-oriented, and doesn't rely on using functions from the older TypInfo unit.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770