title: How to create an instance of object with RTTI in Delphi 2010?
body: <p>As we all known, when we call a constructor of a class like this:</p>
  
  <pre><code>instance := TSomeClass.Create;
  </code></pre>
  
  <p>The Delphi compiler actually do the following things:</p>
  
  <ol>
  <li>Call the static NewInstance method
  to allocate memory and initialize
  the memory layout.</li>
  <li>Call the constructor method to
  perform the initialization of the class</li>
  <li>Call the AfterConstruction method</li>
  </ol>
  
  <p>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.</p>
  
  <p>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.</p>
  
  <pre><code>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;
  </code></pre>
  
  <p>I feel it maybe not 100% right. so please show me the way. Thanks!</p>