As we all known, when we call a constructor of a class like this:
instance := TSomeClass.Create;
The Delphi compiler actually do the follow
Invoking the constructor and passing the class as the Self
argument (as opposed to an instance) will correctly construct the class. The process of constructing includes the NewInstance
, AfterConstruction
etc. that you are manually doing here: it's not necessary.
This ought to be sufficient:
Result := constructorMethod.Invoke(instanceType.MetaclassType, arguments);
An oddity of Delphi is how it permits constructors to be called on instances as well as classes. This feature is used as a kind of "placement new" (in C++ terminology) for form construction, so that the global form variable (e.g. Form1
by default for the first form) is assigned at the time that the OnCreate
constructor gets invoked. Thus, your code doesn't raise an exception. But it is more normal to pass the class rather than the instance as the Self
argument.