Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I instantiate a class from its TRttiType?

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.

like image 845
Niyoko Avatar asked Feb 07 '13 02:02

Niyoko


2 Answers

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;
like image 184
RRUZ Avatar answered Oct 03 '22 06:10

RRUZ


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.

like image 45
Remy Lebeau Avatar answered Oct 03 '22 08:10

Remy Lebeau