Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get class by its name in Delphi

I would like to write a function that accepts a classname and results the corresponding TClass. I've noticed that, System.Classes.GetClass function doesn't works if the classname isn't registered.

Example:

if(GetClass('TButton') = nil)
then ShowMessage('TButton not found!')
else ShowMessage('TButton found!');

The previous code always shows:

TButton not found!

Is there something missing?

like image 334
Hwau Avatar asked Oct 18 '25 16:10

Hwau


1 Answers

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;
like image 190
Dalija Prasnikar Avatar answered Oct 20 '25 15:10

Dalija Prasnikar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!