Can I get PTypeInfo from a string?

It will probably be “no,” but is there a way to use Delphi RTTI, either the old school or the extended 2010 RTTI, to pass a string containing the type name, in particular the name of the numbered type, and give me PTypeInfo for that type? I looked at RTTI.pas and TypInfo.pas, and I don't see any function that would do this, but I might have missed something.

What I'm looking for:

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

Or something like that. The thing is, an enumerated type name will be passed; it will not be known at compile time.

+5
source share
1 answer

The following should work with a qualified name.

Qualified Name: 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;
+10
source

All Articles