title: Delphi Rtti: how to get objects from TObjectList<T>
body: <p>I am working a custom class to xml converter and one of the requirements is the ability to stream <code>TObjectList&lt;T&gt;</code> fields.<br>
  I am trying to invoke the <code>ToArray()</code> method to get hold of the TObjectlist's objects, but I get 'Invalid class typecast' because the types obviously don't match.</p>
  
  <p>take this class for example:</p>
  
  <pre><code>type
    TSite = class
      Name : String;
      Address : String; 
    end;
  
    TSites = class
      Sites : TObjecList&lt;TSite&gt;;
    end;  
  </code></pre>
  
  <p>I just need to get the Site Objects from the Sites TObjectList.
  Please keep in mind that I am using RTTI, so I don't know the ObjectType in TObjectList, <strong>so Typecasting won't work</strong>. This is what I have but it seems a dead end (Obj is <code>TobjectList&lt;TSite&gt;</code> here):</p>
  
  <pre><code>function TXmlPersister.ObjectListToXml(Obj : TObject; Indent: String): String;
  
  var
    TypInfo: TRttiType;
    meth: TRttiMethod;
    Arr  : TArray&lt;TObject&gt;;
  
  begin
   Result := '';
   TypInfo := ctx.GetType(Obj.ClassInfo);
   Meth := TypInfo.GetMethod('ToArray');
   if Assigned(Meth) then
    begin
     Arr := Invoke(Obj, []).AsType&lt;TArray&lt;TObject&gt;&gt;; // invalid class typecast error
  
     if Length(Arr) &gt; 0 then
      begin
       // get objects from array and stream them
       ...
      end;
    end;
  </code></pre>
  
  <p>Any way to get the objects out of the TObjectList via RTTI is good for me.
  For some odd reason I don't see the GetItem/SetItem methods in TypInfo</p>
  
  <p><strong>EDIT</strong></p>
  
  <p>Thanks to David I have my solution:</p>
  
  <pre><code>function TXmlPersister.ObjectListToXml(Obj : TObject; Indent: String): String;
  
  var
    TypInfo: TRttiType;
    meth: TRttiMethod;
    Value: TValue;
    Count : Integer;
  
  begin
   Result := '';
   TypInfo := ctx.GetType(Obj.ClassInfo);
   Meth := TypInfo.GetMethod('ToArray');
   if Assigned(Meth) then
    begin
     Value := Meth.Invoke(Obj, []);
     Assert(Value.IsArray);
     Count :=  Value.GetArrayLength;
     while Count &gt; 0 do
      begin
       Dec(Count);
       Result := Result + ObjectToXml(Value.GetArrayElement(Count).AsObject, Indent);
      end;
    end;
  end;
  </code></pre>
  
  <p>I am open for suggestions, maybe there are more 'clever' ways to achieve this goal...</p>