How do I instantiate a class from its TRttiType?

自古美人都是妖i 提交于 2021-02-06 11:09:49

问题


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.


回答1:


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;



回答2:


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.



来源:https://stackoverflow.com/questions/14742505/how-do-i-instantiate-a-class-from-its-trttitype

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!