How to create an instance of object with RTTI in Delphi 2010?

Posted by Paul on Stack Overflow See other posts from Stack Overflow or by Paul
Published on 2010-06-18T10:18:55Z Indexed on 2010/06/18 10:23 UTC
Read the original article Hit count: 284

Filed under:
|
|

As we all known, when we call a constructor of a class like this:

instance := TSomeClass.Create;

The Delphi compiler actually do the following things:

  1. Call the static NewInstance method to allocate memory and initialize the memory layout.
  2. Call the constructor method to perform the initialization of the class
  3. Call the AfterConstruction method

It's simple and easy to understand. but I'm not very sure how the compiler handle exceptions in the second and the third step.

It seems there are no explicit way to create an instance using a RTTI constructor method in D2010. so I wrote a simple function in the Spring Framework for Delphi to reproduce the process of the creation.

class function TActivator.CreateInstance(instanceType: TRttiInstanceType;
  constructorMethod: TRttiMethod; const arguments: array of TValue): TObject;
var
  classType: TClass;
begin
  TArgument.CheckNotNull(instanceType, 'instanceType');
  TArgument.CheckNotNull(constructorMethod, 'constructorMethod');
  classType := instanceType.MetaclassType;
  Result := classType.NewInstance;
  try
    constructorMethod.Invoke(Result, arguments);
  except
    on Exception do
    begin
      if Result is TInterfacedObject then
      begin
        Dec(TInterfacedObjectHack(Result).FRefCount);
      end;
      Result.Free;
      raise;
    end;
  end;
  try
    Result.AfterConstruction;
  except
    on Exception do
    begin
      Result.Free;
      raise;
    end;
  end;
end;

I feel it maybe not 100% right. so please show me the way. Thanks!

© Stack Overflow or respective owner

Related posts about delphi

Related posts about rtti