How to create an instance of a class from its TRttiType?

I want to create a form with the name of my class as a string about which was set earlier , but instead of calling GetClass I want to use the New RTTI function from Delphi.

With this code, I have TRttiType , but I don’t know how to create 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 also tried lType.NewInstance with no luck.

+8
rtti delphi delphi-xe2
source share
2 answers

You must impose TRttiType on the TRttiInstanceType class, and then call the constructor using GetMethod .

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; 
+9
source share

You should use the TRttiContext.FindType() method instead of manually navigating through the TRttiContext.GetTypes() list, for example:

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

But in any case, as soon as you place TRttiType for the desired class type, you can create it this way:

 type TFormBaseClass = class of TFormBase; f := TFormBaseClass(GetTypeData(lType.Handle)^.ClassType).Create(TheDesiredOwnerHere); 

Or this if TFormBase obtained 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, as shown in @RRUZ's figure. This is more TRttiType oriented and does not rely on the use of functions from the older TypInfo module.

+4
source share

All Articles