我正在尋找一種掃描所有加載的類的方法,如果可能的話,包含自定義屬性,而不使用RegisterClass()。掃描給定的自定義屬性的所有類
3
A
回答
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
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
....
相關問題
- 1. 將自定義屬性指定給強定義的MVC類
- 2. 定義自定義掃描運算符
- 3. 如何枚舉具有自定義類屬性的所有類?
- 4. Java - 將項目掃描爲另一個自定義類的自定義類
- 5. 訪問所有自定義DOM屬性
- 6. 訪問自定義依賴屬性的所有屬性PropertyChangedCallback
- 7. 自定義屬性沒有綁定的綁定屬性
- 8. Java程序包掃描器 - 找到具有給定接口的所有類
- 9. 掃描 - hw自定義文檔大小
- 10. 自定義產品類型的自定義屬性
- 11. Magento的loadByAttribute自定義類別屬性
- 12. php:自定義類型的屬性
- 13. 自定義類的Spring @ Value屬性
- 14. ILMerge和類上的自定義屬性
- 15. VBA自定義類,通過屬性值獲取所有對象
- 16. 帶有嵌套屬性的DyanamoDB掃描
- 17. javascript屬性描述符支持自定義屬性嗎?
- 18. JarScan掃描所有子文件夾中的特定類的所有JAR文件
- 19. 獲取具有自定義屬性的所有Sitecore用戶
- 20. 如何檢查具有自定義屬性的所有輸入
- 21. Swift類自定義類型屬性
- 22. DialogPreference的自定義屬性
- 23. ListProperty的自定義屬性
- 24. 自定義屬性的System.Windows.Window
- 25. UIButton的自定義屬性
- 26. 自定義屬性
- 27. 自定義屬性
- 28. 自定義屬性
- 29. 引用屬性的自定義屬性
- 30. 如何定義類類型的約束如果它具有自定義屬性?
對於它的價值,行'ctx:= TRttiContext.Create();'是根本不需要的。你可以愉快地刪除它! – 2012-02-29 09:25:30
您的示例代碼不完整。提供要使用TMyAttribute進行註釋的類。 – menjaraz 2012-02-29 09:26:46
@menjaraz不,這不是必需的。這是完整的答案。 – 2012-02-29 09:31:04