Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 204
Haruki Avatar asked Oct 20 '11 11:10

Haruki


1 Answers

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;
like image 126
RRUZ Avatar answered Sep 19 '22 00:09

RRUZ