Get class by its name in Delphi

房东的猫 提交于 2019-12-06 03:04:56

You can get unregistered class used in Delphi application via extended RTTI. But you have to use fully qualified class name to find the class. TButton will not be enough, you have to search for Vcl.StdCtrls.TButton

uses
  System.Classes,
  System.RTTI;

var
  c: TClass;
  ctx: TRttiContext;
  typ: TRttiType;
begin
  ctx := TRttiContext.Create;
  typ := ctx.FindType('Vcl.StdCtrls.TButton');
  if (typ <> nil) and (typ.IsInstance) then c := typ.AsInstance.MetaClassType;
  ctx.Free;
end;

Registering class ensures that class will be compiled into Delphi application. If class is not used anywhere in code and is not registered, it will not be present in application and extended RTTI will be of any use in that case.

Additional function that will return any class (registered or unregistered) without using fully qualified class name:

uses
  System.StrUtils,
  System.Classes,
  System.RTTI;

function FindAnyClass(const Name: string): TClass;
var
  ctx: TRttiContext;
  typ: TRttiType;
  list: TArray<TRttiType>;
begin
  Result := nil;
  ctx := TRttiContext.Create;
  list := ctx.GetTypes;
  for typ in list do
    begin
      if typ.IsInstance and (EndsText(Name, typ.Name)) then
        begin
          Result := typ.AsInstance.MetaClassType;
          break;
        end;
    end;
  ctx.Free;
end;
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!