Delphi下获取RTTI信息源代码

本文介绍如何使用 Delphi 的运行时类型信息 (RTTI) 来获取类的基本信息及属性详情,包括类名、类型、大小等,并通过示例展示了获取属性名称和类型的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

procedure GetBaseClassInfo(AClass: TObject; AStrings: TStrings);
{ This method obtains some basic RTTI data from the given 
object and adds that
  information to the AStrings parameter. }
var
  ClassTypeInfo: PTypeInfo;
  ClassTypeData: PTypeData;
  EnumName: String;
begin
  ClassTypeInfo :
= AClass.ClassInfo;
  ClassTypeData :
= GetTypeData(ClassTypeInfo);
  with AStrings 
do
  begin
    Add(Format(
'Class Name:     %s', [ClassTypeInfo.Name]));
    EnumName :
= GetEnumName(TypeInfo(TTypeKind), Integer(ClassTypeInfo.Kind));
    Add(Format(
'Kind:           %s', [EnumName]));
    Add(Format(
'Size:           %d', [AClass.InstanceSize]));
    Add(Format(
'Defined in:     %s.pas', [ClassTypeData.UnitName]));
    Add(Format(
'Num Properties: %d',[ClassTypeData.PropCount]));
  end;
end;

 

 

procedure GetClassProperties(AClass: TObject; AStrings: TStrings);
{ This method retrieves the property names and types 
for the given object
  and adds that information to the AStrings parameter. }
var
  PropList: PPropList;
  ClassTypeInfo: PTypeInfo;
  ClassTypeData: PTypeData;
  i: integer;
  NumProps: Integer;
begin

  ClassTypeInfo :
= AClass.ClassInfo;
  ClassTypeData :
= GetTypeData(ClassTypeInfo);

  
if ClassTypeData.PropCount <> 0 then
  begin
    
// allocate the memory needed to hold the references to the TPropInfo
    
// structures on the number of properties.
    GetMem(PropList, SizeOf(PPropInfo) * ClassTypeData.PropCount);
    
try
      
// fill PropList with the pointer references to the TPropInfo structures
      GetPropInfos(AClass.ClassInfo, PropList);
      
for i := 0 to ClassTypeData.PropCount - 1 do
        
// filter out properties that are events ( method pointer properties)
        if not (PropList[i]^.PropType^.Kind = tkMethod) then
          AStrings.Add(Format(
'%s: %s', [PropList[i]^.Name, PropList[i]^.PropType^.Name]));

      
// Now get properties that are events (method pointer properties)
      NumProps := GetPropList(AClass.ClassInfo, [tkMethod], PropList);
      
if NumProps <> 0 then begin
        AStrings.Add(
'');
        AStrings.Add(
'   EVENTS   ================ ');
        AStrings.Add(
'');
      end;
      
// Fill the AStrings with the events. 
      for i := 0 to NumProps - 1 do
          AStrings.Add(Format(
'%s: %s', [PropList[i]^.Name, PropList[i]^.PropType^.Name]));

    
finally
      FreeMem(PropList, SizeOf(PPropInfo) 
* ClassTypeData.PropCount);
    end;
  end;

end;

 

 运用Delphi 的 RTTI可以实现 Java 与 C# 下的反射机制,只是大家在Delphi 下做 RAD开发做多了,没有关注到这些关键的技术,接下来会写一个Delphi 下的OR Mapping框架,到时候会与大家分享。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值