Search code examples
delphirttidelphi-10.1-berlin

Returning an ObjectList from RTTI in delphi


i'm calling method inside an object and i'm trying to stay very dynamic in the way i'm doing it and i came to a problem where my return type is a list of some objects, i thought about using TObjectList the problem now is that rtti returns a TValue and i don't fully understand how i can convert it to TObjectList. I thought casting the TValue as TObject since theoritically TObjectList is an object but it didn't work. Do you guys have any idea how i can possibly achieve this?

That's the function i'm speaking about.

   function TMyClass.ExecMethodAndRet(MethodName: string;
      Args: array of TValue): TObjectList<TObject>;
    var
     R : TRttiContext;
     T : TRttiType;
     M : TRttiMethod;
    begin
      T := R.GetType(FMyObject.ClassInfo);
      for M in t.GetMethods do
        if (m.Parent = t) and (UpperCase(m.Name) = UpperCase(MethodName))then
        begin
          result := M.Invoke(FMyObject, Args); <- problem here can't cast to TObjectList
        end;
    end;

Solution

  • Return:

    Result := M.Invoke(Self, Args).AsType<TObjectList<TObject>>;
    

    P.S. don't forget to initialize return value, ideally at the beginning of your function body.