Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access RTTI in a class constructor?

This code is not allowed:

class constructor TOmniMultiPipelineStage.Create;
var
  RTTIType: TRttiType;
begin
  RTTIType:= TRttiContext.GetType(self);
end;

[dcc32 Error] OtlParallel.pas(5040): E2003 Undeclared identifier: 'self'

The variant is also not allowed:

class constructor TOmniMultiPipelineStage.Create;
var
  RTTIType: TRttiType;
begin
  //Not really what I want because I want the actual type of the class
  //Not a fixed ancestor type 
  RTTIType:= TRttiContext.GetType(TOmniMultiPipelineStage);
end;

[dcc32 Error] OtlParallel.pas(5039): E2076 This form of method call only allowed for class methods or constructor

How do I get RTTI info on a class in its class constructor?

Note to self: loop over all descendants of a class: Delphi: At runtime find classes that descend from a given base class?

like image 1000
Johan Avatar asked Oct 20 '22 05:10

Johan


1 Answers

Use the ClassInfo class method of TObject:

class constructor TMyClass.ClassCreate;
var
  ctx: TRttiContext;
  typ: TRttiType;
begin
  typ := ctx.GetType(ClassInfo);
end;

Note that I also fixed the syntax of your call to GetType, which is an instance method, and so must be called on an instance of TRttiContext.

A bigger problem for you is that class constructors are not going to be of use to you. A class constructor is static. They execute once only, for the type that defines them. They do not execute in the context of derived classes, as you are clearly expecting.

And likewise for class vars, which you discuss in the comments. There is but a single instance of a class var. You are expecting and hoping that there will be new instances for each derived class.

So whilst ClassInfo answers the question you asked, it won't be of any real use to you.

like image 64
David Heffernan Avatar answered Oct 31 '22 21:10

David Heffernan