uses
System.SysUtils, System.TypInfo, System.Rtti;
type
IWidget<T> = interface
procedure SetInstance(const Inst: T);
end;
TWidgetImpl<T> = class(TInterfacedObject, IWidget<T>)
public
procedure SetInstance(const Inst: T);
end;
{ TWidgetImpl<T> }
procedure TWidgetImpl<T>.SetInstance(const Inst: T);
var
ctx: TRttiContext;
typ: TRttiType;
m: TRttiMethod;
begin
typ := ctx.GetType(TypeInfo(T));
m := typ.GetMethod('Initialize');
if (Assigned(m)) then
begin
m.Invoke(TValue.From<T>(Inst), []);
end;
end;
type
TObjInst = class
public
procedure Initialize;
end;
{ TObjInst }
procedure TObjInst.Initialize;
begin
WriteLn('TObjInst.Initialize');
end;
type
IIntfInst = interface(IInvokable)
procedure Initialize;
end;
TIntfInstImpl = class(TInterfacedObject, IIntfInst)
public
procedure Initialize;
end;
{ TIntfInstImpl }
procedure TIntfInstImpl.Initialize;
begin
WriteLn('IIntfInst.Initialize');
end;
var
wo: IWidget<TObjInst>;
o: TObjInst;
wi: IWidget<IIntfInst>;
i: IIntfInst;
begin
wo := TWidgetImpl<TObjInst>.Create;
o := TObjInst.Create;
wo.SetInstance(o);
wi := TWidgetImpl<IIntfInst>.Create;
i := TIntfInstImpl.Create;
wi.SetInstance(i);
ReadLn;
end.