Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RTTI: Can I Get a Type by Name?

Given a text string containing a type name, is there some way to get the appropriate type itself?

I'm looking to do something like this:

type
  TSomeType<T> = class
    // yadda yadda
  end;

procedure DoSomething;
var
  obj : TObject;
begin
  o := TSomeType<GetTypeByName('integer')>.Create;
  // do stuff with obj
end;

I've looked at several RTTI explanations online and looked through the Delphi units and don't see what I'm looking for. Is this possible?

like image 676
TrespassersW Avatar asked Dec 04 '22 14:12

TrespassersW


2 Answers

No, generics are entirely compiletime.

like image 185
Marco van de Voort Avatar answered Dec 26 '22 06:12

Marco van de Voort


The new RTTI unit in Delphi 2010 has a way of retrieving types declared in the interface section of units. For any given type, represented by a TRttiType instance, the TRttiType.QualifiedName property returns a name that can be used with TRttiContext.FindType later to retrieve the type. The qualified name is the full unit name (including namespaces, if they exist), followed by a '.', followed by the full type name (including outer types if it nested).

So, you could retrieve a representation of the Integer type (in the form of a TRttiType) with context.FindType('System.Integer').

But this mechanism can't be used to retrieve instantiations of generic types that weren't instantiated at compile time; instantiation at runtime requires runtime code generation.

like image 43
Barry Kelly Avatar answered Dec 26 '22 08:12

Barry Kelly