How do I instantiate a class from its TRttiType?

前端 未结 2 546
逝去的感伤
逝去的感伤 2021-02-09 01:44

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 featu

相关标签:
2条回答
  • 2021-02-09 02:24

    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;
    
    0 讨论(0)
  • 2021-02-09 02:38

    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.

    0 讨论(0)
提交回复
热议问题