I've got two questions (of which at least one is regarding RTTI in D2010 and dynamic instancing)
TRTTIConstructor.Invoke
. In an adjacent bullet point, one finds "Dynamically construct instances without needing virtual constructors and metaclasses". This seems like a great feature (and exactly what I need, btw)! However, when I look in the D2010 docs (ms-help://embarcadero.rs2010/vcl/Rtti.html), I can't find it. Did it get revoked? I think that functionality has been absorbed into TRttiMethod. It has IsConstructor, IsDestructor and IsClassMethod properties so that it can be used for "special" types of methods as well as normal ones.
As for question 2, try something like this:
function GetConstructor(val: TRttiInstanceType): TRttiMethod;
var
method: TRttiMethod;
begin
for method in val.GetMethods('Create') do
begin
if (method.IsConstructor) and (length(method.GetParameters) = 0) then
exit(method);
end;
raise EInsufficientRTTI.CreateFmt('No simple constructor available for class %s ',
[val.MetaclassType.ClassName]);
end;
This finds the highest constructor called Create
that takes no parameters. You can modify it to look for other constructors with other signatures, if you know what you're looking for. Then just call Invoke
on the result.
Although you can call .GetMethod() to get the constructor you can also do the following to construct instances of objects with no parameters for the constructor.
function CreateInstance(aType : TRttiType) : TObject;
begin
// Option #1
result := aType.AsInstance.MetaclassType.Create;
// Option #2
result := aType.GetMethod('Create').Invoke(aType.AsInstance.MetaclassType,[]);
end;
If know the base type you can type cast the class to pass the parameters if you wish. Here is an example of creating a Component
result := TComponentClass(aType.AsInstance.MetaClassType).Create(OwnerValue);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With