Delphi use reflection in a class procedure for the getting dynamic class type
Asked Answered
C

1

4

I want use reflection on the current class inside a class procedure/function (static method). How can I do without using the "Self" keyword? And without harcode the class name: this procedure should be override in the descendants.

class procedure AAA.SetTableAndSequence;
var
c : TRttiContext;
t : TRttiType;
begin
  c := TRttiContext.Create;
  try
    t := c.GetType(Self.ClassType);
    ...
  finally
   c.Free;
  end;
end;
Cankerous answered 3/7, 2014 at 16:30 Comment(1)
FWIW, the try/finally is pointless here. TRttiContext is not a class. Just use c directly. It auto-initializes.Trilley
E
4

You can use ClassInfo and GetType:

class procedure AAA.SetTableAndSequence;
var
  c: TRttiContext;
  t: TRttiType;
begin
  t := c.GetType(ClassInfo);
  ...
end;
Ensue answered 4/7, 2014 at 5:50 Comment(2)
What exactly is the value returned by ClassInfo? Is it the same thing that a TypeInfo would return? Oh and thanks for pointing out that my now deleted answer was bogus.Trilley
Yes, the VMT contains a field to the TypeInfo of a class (vmtTypeInfo slot) which is returned by the ClassInfo class function.Ensue

© 2022 - 2024 — McMap. All rights reserved.