Quando estamos programando Orientado a Objeto, as vezes precisamos verificar o Tipo, Valor e Nome de um Objeto. Estarei demonstrando de forma simples e objetiva como extrair de uma classe estas informações em Run-Time. Como exemplo, criei a Classe TPessoa, com 3 propriedades(Campos: Codigo, Nome, Nascimento) e em seguida faço a listagem desses campos numa TStringList.
Inicie um novo projeto, adicione um TButton e um TMemo no Form.
Para capturar tais propriedades devemos declarar no USES a biblioteca "TypInfo",
que é responsável
pelo acesso em Run-Time aos Objetos.
Feito isso crie a Classe TPessoa:
unit uPessoa;
interface
uses
SysUtils, Classes, Controls;
type TPessoa = class(TComponent)
private
FCodigo: Integer;
FNome: String;
FNascimento: TDate;
function GerCodigo: Integer;
function GetNome: String;
procedure SetCodigo(const Value: Integer);
procedure SetNome(const Value: String);
function GetNascimento: TDate;
procedure SetNascimento(const Value: TDate);
public
constructor Create(AOwner: TObject);
destructor Destroy; override;
published
property Codigo: Integer read GerCodigo write SetCodigo;
property Nome: String read GetNome write SetNome;
property Nascimento: TDate read GetNascimento write SetNascimento;
end;
implementation
{ TPessoa }
constructor TPessoa.Create(AOwner: TObject);
begin
FCodigo := 1;
FNome := 'Teste RTTI';
FNascimento := Date;
end;
destructor TPessoa.Destroy;
begin
inherited Destroy;
end;
function TPessoa.GerCodigo: Integer;
begin
Result := FCodigo;
end;
function TPessoa.GetNascimento: TDate;
begin
Result := FNascimento;
end;
function TPessoa.GetNome: String;
begin
Result := FNome;
end;
procedure TPessoa.SetCodigo(const Value: Integer);
begin
FCodigo := Value;
end;
procedure TPessoa.SetNascimento(const Value: TDate);
begin
FNascimento := Value;
end;
procedure TPessoa.SetNome(const Value: String);
begin
FNome := Value;
end;
end.
Repare que é uma estrutura básica de Classe, herdando da Classe
TComponent.
Vale lembrar que só conseguimos capturar tais propriedades pois elas
estão declaradas na sessão Public da classe TPessoa ("property").
Em seguida criaremos uma procedure que fará a Leitura da Clase:
procedure ListComponentProperties(Component: TComponent; Strings: TStrings);
var
Count, Size, I: Integer;
List: PPropList;
PropInfo: PPropInfo;
PropOrEvent, PropValue: string;
begin
{ Conto quantas propriedade e métodos o component possui }
Count := GetPropList(Component.ClassInfo, tkAny, nil);
{ Aponto para o Endereço de memória }
Size := Count * SizeOf(Pointer);
GetMem(List, Size);
try
{ Conto quantas propriedade e métodos o component possui passando os dados para a Lista}
Count := GetPropList(Component.ClassInfo, tkAny, List);
{ Varro as propridades e métodos }
for I := 0 to Count - 1 do
begin
PropInfo := List^[I];
{ Verifico se é um Evento ou Propriedade }
if PropInfo^.PropType^.Kind in tkMethods then
PropOrEvent := 'Event'
else
PropOrEvent := 'Property';
{ Caso a propriedade seja string, então mudo seu Valor }
if (PropOrEvent = 'Property') and (PropInfo^.PropType^.Name = 'String') then
SetPropValue(Component,PropInfo^.Name,'FELIPE');
{ Capturo o Valor da Propriedade }
PropValue := VarToStr(GetPropValue(Component, PropInfo^.Name));
{ Mostro se é prop. ou Evento, Nome, Tipo e Valor }
if (PropInfo^.Name <> 'Name') and (PropInfo^.Name <> 'Tag') then
Strings.Add( Format('[%s] %s: %s = %s',
[PropOrEvent, PropInfo^.Name,
PropInfo^.PropType^.Name, PropValue]));
end;
finally
{ Libero a memória }
FreeMem(List);
end;
end;
Como vemos, estamos capturando as propriedades e eventos da Instancia, seus
tipos e valores, e além disso manipulando determinada informação.
No Evento OnClick do botão, criaremos uma Instância da classe
TPessoa:
procedure TForm1.Button1Click(Sender: TObject);
var
Pessoa: TPessoa;
begin
{ Listar Propriedades da Pessoa }
Pessoa := TPessoa.Create(Self);
try
Memo1.Clear;
ListComponentProperties(Pessoa,Memo1.Lines);
finally
Pessoa.Free;
end;
end;
Agora, se você fez tudo corretamente, compile o projeto e o execute.
Clique no botão e no memo deve aparecer as seguintes respostas:
[Property] Codigo: Integer = 1
[Property] Nascimento: TDate = 39106
[Property] Nome: String = FELIPE
Este é o princípio básico do RTTI. Espero que os ajudem
em seus projetos!
|