I am creating a routine to instantiate a class via RTTI
and validate if this class implements a interface
.
I have a test class implemented as follows:
unit teste.classeTeste.uclasseTeste;
interface
uses
validador;
type
ClasseTeste = class(TInterfacedObject, IServico)
private
public
function foo: string;
end;
implementation
{ classe }
function ClasseTeste.foo: string;
begin
Result := 'Teste foo';
end;
initialization
ClasseTeste.ClassName;
end.
And I have a Validator class implemented as follows:
unit validador;
interface
uses
Rtti;
type
IServico = interface
['{46C26FED-AEDD-456F-B182-DEECB780D264}']
end;
Svc = class
public
function Validar(pClassName: string): Boolean;
end;
implementation
uses
SysUtils;
{ Svc }
function Svc.Validar(pClassName: string): Boolean;
var
lContext: TRttiContext;
lType: TRttiInstanceType;
lObj: TObject;
begin
Result := False;
lType := lContext.FindType(pClassName) as TRttiInstanceType;
if lType = nil then
raise Exception.Create('Classe solicitada não encontrada no sistema ou ClassNameInválido');
lObj := lType.GetMethod('Create').Invoke(lType.MetaclassType, []).AsObject;
try
if not Supports(lObj, IServico) then
raise Exception.Create('A classe serviço não implementa a interface IServico!');
finally
lObj.Free;
end;
Result := True;
end;
end.
The question is: In the Validate method on the
'lObj.Free';
It bursts
"Invalid Pointer Operation".
Theoretically I have a TObject
instantiated. It needs to be released sometime. How and when do I release it?
Note: I'm using Delphi 2010.