java中的反射机制使我们能够在运行期间获取运行期类的信息,那么在delphi中有没有这样的功能呢?答案是有,实现这种功能的机制在delphi中叫做RTTI,废话少说,先来一段demo:
1.先定义一个demo类,注意这个类必须要以TPersistent为基类,代码如下:
unit Unit2; interface { TDemo } uses Classes ; type TDemo = class(TPersistent) private protected public FName : string; FAge : Integer; constructor Create; destructor Destroy; override; published property Name : string read FName write FName; property Age : Integer read FAge write FAge; end; implementation { TDemo } constructor TDemo.Create; begin FName := 'peirenlei'; end; destructor TDemo.Destroy; begin inherited; end; end.
2.接下来,创建一个这个类的实例:
ADemo := TDemo.Create; ADemo.Name := 'peirenlei'; ADemo.Age := 0;
3.获取该实例的属性列表:
var APropList:PPropList; ATypeInfo:PTypeInfo; AClasDateInfo:PTypeData; I : Integer; begin ATypeInfo := ADemo.ClassInfo; AClasDateInfo := GetTypeData(ATypeInfo); if AClasDateInfo.PropCount <> 0 then begin //分配空间 GetMem(APropList,sizeof(PPropInfo)*AClasDateInfo.PropCount); try GetPropInfos(ADemo.ClassInfo,APropList); //得到类的属性列表 for I := 0 to AClasDateInfo.PropCount - 1 do begin if APropList[I]^.PropType^.Kind <> tkMethod then mmo.Lines.Add(Format('%s:%s',[APropList[I]^.Name,APropList[I]^.PropType^.Name])); end; finally FreeMem(APropList,sizeof(APropList)*AClasDateInfo.PropCount); end; end; end;
输出:
Name:string Age:Integer
3. 获取类的方法列表:
var APropList:PPropList; ATypeInfo:PTypeInfo; AClasDateInfo:PTypeData; I ,NumPro : Integer; begin ATypeInfo := ADemo.ClassInfo; AClasDateInfo := GetTypeData(ATypeInfo); if AClasDateInfo.PropCount <> 0 then begin //分配空间 GetMem(APropList,sizeof(PPropInfo)*AClasDateInfo.PropCount); try NumPro := GetPropList(ADemo.ClassInfo,[tkMethod],APropList); if NumPro <> 0 then begin mmo.Lines.Add('-----events-------'); for I := 0 to NumPro - 1 do //获得事件属性的列表 begin mmo.Lines.Add(Format('%s:%s',[APropList[i]^.Name,APropList[i]^.PropType^.Name])); end; end; finally FreeMem(APropList,sizeof(PPropInfo)*AClasDateInfo.PropCount); end; end; end;
4.获取实例类的属性和属性值:
var AProperInfo:PPropInfo; AValue:string; begin AValue := GetPropValue(ADemo,'Name'); mmo.Lines.Add('Name='+AValue); AValue := GetPropValue(ADemo,'Age'); mmo.Lines.Add('Age='+AValue); SetPropValue(ADemo,'Name','zengzhen'); SetPropValue(ADemo,'Age',100); AValue := GetPropValue(ADemo,'Name'); mmo.Lines.Add('Name='+AValue); AValue := GetPropValue(ADemo,'Age'); mmo.Lines.Add('Age='+AValue); end;
输出:
Name=peirenlei Age=0 Name=zengzhen Age=100