Davide Visconti 5 Posted December 7, 2018 type TMyClass = class public procedure Run; end; TMyTool = class public MyClass: TMyClass; constructor Create; end; ... var MyTool: TMyTool; procedure TFrmMain.FormCreate(Sender: TObject); begin MyTool := TMyTool.Create; end; procedure TFrmMain.Btn1Click(Sender: TObject); var LCtx : TRttiContext; LType1 : TRttiType; LField1 : TRttiField; LNestedType1 : TRttiType; LRttiInstanceType: TRttiInstanceType; LMeth : TRttiMethod; begin LCtx := TRttiContext.Create; LType1 := LCtx.GetType(MyTool.ClassType); LField1 := LType1.GetField('MyClass'); LNestedType1 := LCtx.GetType(LField1.FieldType.Handle); LMeth := LNestedType1.GetMethod('Run'); // LMeth.Invoke(MyTool.MyClass, []); // <-- ok LMeth.Invoke(LNestedType1.AsInstance, []); // <-- fail end; I get "invalid class typecast" I understand where is the problem but I don't know how to resolve it. I have to call the method "MyClass.Run" through RTTI. Can you help me please? Any suggestion will be appreciated. Thank you. Share this post Link to post
Davide Visconti 5 Posted December 7, 2018 This work. Do you have any suggestions? procedure TFrmMain.Btn1Click(Sender: TObject); var LCtx : TRttiContext; LType1 : TRttiType; LField1 : TRttiField; LNestedType1 : TRttiType; LRttiInstanceType: TRttiInstanceType; LMeth : TRttiMethod; LObj : TObject; begin LCtx := TRttiContext.Create; LType1 := LCtx.GetType(MyTool.ClassType); LField1 := LType1.GetField('MyClass'); LObj := LField1.GetValue(MyTool).AsObject; LNestedType1 := LCtx.GetType(LField1.FieldType.Handle); LMeth := LNestedType1.GetMethod('Run'); // LMeth.Invoke(MyTool.MyClass, []); // ok // LMeth.Invoke(LNestedType1.AsInstance.ClassInfo, []); // fail LMeth.Invoke(LObj, []); end; Share this post Link to post
Kryvich 165 Posted December 7, 2018 procedure Run is a method of object, not a class method. So you need an object instance to call the method. Share this post Link to post
Davide Visconti 5 Posted December 8, 2018 Yes of course. Thanks @Kryvich Share this post Link to post