Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I get a PTypeInfo from a string?

Tags:

delphi

rtti

This is probably going to be a "no", but is there any way I can use Delphi's RTTI, either old-school or the 2010 extended RTTI, to pass in a string containing the name of a type, specifically the name of an enumerated type, and have it give me the PTypeInfo for that type? I've looked through RTTI.pas and TypInfo.pas and I don't see any function that would do that, but I might have missed something.

What I'm looking for:

var
  info: PTypeInfo;
begin
  info := GetTypeInfoFromName('TComponentStyle');
end;

Or something like that. Thing is, the name of the enumerated type would be passed in; it wouldn't be known at compile time.

like image 388
Mason Wheeler Avatar asked May 26 '10 17:05

Mason Wheeler


1 Answers

The following should work with the qualified name.

Qualified Name is: UnitName.TypeName

type
 ETypeNotFound = class(Exception);

function GetTypeInfoFromName(aTypeName : String) : pTypeInfo;
var
 C : TRttiContext;
 T : TRttiType;
begin
 T := C.FindType(aTypeName);
 if Not Assigned(T) then
    raise ETypeNotFound.CreateFmt('Type %s is not found',[aTypeName]);

 result := T.Handle;
end;
like image 182
Robert Love Avatar answered Nov 02 '22 18:11

Robert Love