How do I instantiate a class from its TRttiType?
Asked Answered
S

2

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.

Sketchy answered 7/2, 2013 at 2:24 Comment(0)
V
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;
Vicarious answered 7/2, 2013 at 3:0 Comment(3)
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;Wendelina
@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;Vicarious
Sorry, I didn't notice that f was a TValue, I was looking at Niyoko's code when I saw that.Wendelina
W
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.

Wendelina answered 7/2, 2013 at 3:2 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.