Search code examples
listdelphireflectiontlist

Check if a Field is a TList with Reflection


Using Delphi how can I check if a field of an object is a TList ?

I tryed using this

var
  c : TRttiContext;
  t : TRttiType;
  f : TRttiField;
begin
  c := TRttiContext.Create;
    t := c.GetType(Self.ClassType);
    for f in t.GetFields do begin
      //check if the field is TList<T>
      //check also the Generic type T 
    end;
end;

Solution

  • You have to use the IsType<T> method if you want to check for TList (the one from System.Classes).

    If you want to check if it is a TList<T> you have to do some string parsing of the class name. Even more so if you want to check the specific type of T. This is because Delphi has no special RTTI about generic types and it does not support open generic types.

    You can look at the Spring.Helpers unit from Spring4D how this can be solved.

    Some example code using this:

    if f.FieldType.IsGenericType then
      if f.FieldType.GetGenericTypeDefinition = 'TList<>' then
        if f.FieldType.GetGenericArguments[0].Handle = TypeInfo(TMyClass) then
          Writeln('found');