2012-02-29 62 views

回答

7

首先,您必須創建TRttiContext,然後使用getTypes獲取所有加載的類。之後,您可以按照TypeKind = tkClass過濾類型; 下一步是枚舉屬性並檢查它是否具有屬性;

屬性和測試類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. 

,然後找到它:

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. 

輸出Unit3.TTest

呼叫的RegisterClass與流系統註冊類。 ...一旦註冊了類,它們就可以被組件流系統加載或保存。

所以如果你不需要組件流(隨便找一些屬性類),就沒有必要RegisterClass

+0

對於它的價值,行'ctx:= TRttiContext.Create();'是根本不需要的。你可以愉快地刪除它! – 2012-02-29 09:25:30

+0

您的示例代碼不完整。提供要使用TMyAttribute進行註釋的類。 – menjaraz 2012-02-29 09:26:46

+0

@menjaraz不,這不是必需的。這是完整的答案。 – 2012-02-29 09:31:04

4

您可以使用由RTTI單元中曝光的新RTTI功能。

var 
    context: TRttiContext; 
    typ: TRttiType; 
    attr: TCustomAttribute; 
    method: TRttiMethod; 
    prop: TRttiProperty; 
    field: TRttiField; 
begin 
    for typ in context.GetTypes do begin 
    for attr in typ.GetAttributes do begin 
     Writeln(attr.ToString); 
    end; 

    for method in typ.GetMethods do begin 
     for attr in method.GetAttributes do begin 
     Writeln(attr.ToString); 
     end; 
    end; 

    for prop in typ.GetProperties do begin 
     for attr in prop.GetAttributes do begin 
     Writeln(attr.ToString); 
     end; 
    end; 

    for field in typ.GetFields do begin 
     for attr in field.GetAttributes do begin 
     Writeln(attr.ToString); 
     end; 
    end; 
    end; 
end; 

此代碼枚舉與方法,屬性和字段以及類型關聯的屬性。當然,你會想要做的比Writeln(attr.ToString),但這應該給你一個如何進行的想法。你可以用正常的方式測試你的特定屬性

if attr is TMyAttribute then 
    ....