Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scan all classes for a given custom attribute

I'm looking for a way of scanning all loaded classes for classes which contain a custom attribute, if possible, without using RegisterClass().

like image 758
Marius Avatar asked Mar 06 '26 01:03

Marius


1 Answers

at first you have to create TRttiContext, then get all loaded classes using getTypes. after that you can filter types by TypeKind = tkClass; next step is to enumerate attributes and check if it has your attribute;

attribute and test-class delcaration:

unit Unit3;

interface
type
    TMyAttribute = class(TCustomAttribute)
    end;

    [TMyAttribute]
    TTest = class(TObject)

    end;

implementation

initialization
    TTest.Create().Free();  //if class is not actually used it will not be compiled

end.

and then find it:

program Project3;
{$APPTYPE CONSOLE}

uses
  SysUtils, rtti, typinfo, unit3;

type TMyAttribute = class(TCustomAttribute)

     end;

var ctx : TRttiContext;
    t : TRttiType;
    attr : TCustomAttribute;
begin
    ctx := TRttiContext.Create();

    try
        for t  in ctx.GetTypes() do begin
            if t.TypeKind <> tkClass then continue;

            for attr in t.GetAttributes() do begin
                if attr is TMyAttribute then begin
                    writeln(t.QualifiedName);
                    break;
                end;
            end;
        end;
    finally
        ctx.Free();
        readln;
    end;
end.

output is Unit3.TTest

Call RegisterClass to register a class with the streaming system.... Once classes are registered, they can be loaded or saved by the component streaming system.

so if you don't need component streaming (just find classes with some attribute), there is no need to RegisterClass

like image 200
teran Avatar answered Mar 08 '26 19:03

teran



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!