You can do this with RTTI:
uses System.Rtti; .... function TClassA<T>.Duplicate: IBla<T>; var ctx: TRttiContext; typ: TRttiType; mthd: TRttiMethod; inst: TValue; begin typ := ctx.GetType(ClassInfo); mthd := typ.GetMethod('Create'); inst := mthd.Invoke((typ as TRttiInstanceType).MetaclassType, []); inst.AsObject.GetInterface(IBla<T>, Result); end;
There is, perhaps, a cleaner way to invoke the constructor using RTTI (I know almost nothing about RTTI in Delphi), so you might think that you are reading this topic, and not considering it in a canonical way. this.
Of course, this assumes that all subclasses use the parameterless constructor defined in TObject
. This can be quite limited. I would not be surprised if you have to rethink design in a more fundamental way.
If none of your subclasses implements constructors, you can make it even simpler and not use RTTI at all:
function TClassA<T>.Duplicate: IBla<T>; begin ClassType.Create.GetInterface(IBla<T>, Result); end;
But keep in mind that this calls the constructor defined in TObject
and will not call the constructor defined in the subclass.
source share