How to get the class type reference by its name in Delphi XE?

徘徊边缘 提交于 2019-12-12 08:53:50

问题


I'm actually trying to use Rtti to implent a generic method invoker. It should work like this:

  • I'll provide the class name, method name, and arguments
  • the invoker will do its work by invoking the specified method of this class

So I need the class reference in order to get its Rtti information and seek for the method I want to invoke.

Is there any way to do that without implementing a class reference list of the classes I want to be working with?


回答1:


To get the class reference using his name you must use the TRttiContext.FindType function passing the Name of the class and the retrieve the instance using the AsInstance property and then you can call the constructor of the class.

var
  Instance : TRttiInstanceType;
  ctx : TRttiContext;
  mClass : TValue;
begin
  ctx := TRttiContext.Create;   
  Instance := ctx.FindType(ClassName).AsInstance; //ClassName is something like  'Classes.TStringList';
  mClass := Instance.GetMethod('Create').Invoke(Instance.MetaclassType,[]);

   //do your stuff here


end;


来源:https://stackoverflow.com/questions/7835324/how-to-get-the-class-type-reference-by-its-name-in-delphi-xe

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