Why does FindType fail to get RTTI when GetType succeeds?
Asked Answered
E

1

3

I'm trying to get hold of an object using TRttiContext.FindType(QualifiedTypeName). Here's what I've got:

program MissingRTTI;
{$APPTYPE CONSOLE}
uses System.SysUtils, RTTI, Classes;
type
  TMyClass = class(TObject) end;
var
  rCtx:   TRttiContext;
  rType:  TRttiInstanceType;
begin
  rCtx := TRttiContext.Create();
  rType := rCtx.GetType(TypeInfo(TMyClass)) as TRttiInstanceType;
  if (rType <> nil) then begin
    WriteLn('Type found using TypeInfo');
  end;
  rType := rCtx.FindType(TMyClass.QualifiedClassName) as TRttiInstanceType;
  if (rType <> nil) then begin
    WriteLn('Type found using qualified class name.');
  end;
  ReadLn;
  rCtx.Free();
end.

Unfortunately, only rCtx.GetType seems to find the desired type. (I've also tried to list all types using GetTypes. The desired type does not appear in the resulting array.) Anyone know how to force the compiler to emit RTTI for this type?

Echelon answered 15/5, 2012 at 11:57 Comment(0)
D
7

Your call to the FindType method doesn't return Rtti info because this function works only for public types. So if you check the rType.IsPublicType property the value returned is false .

The public types must be declarated in the interface section of a unit (to be recognized as public). So if you move the TMyClass class definition to the interface part of a unit you will able to use the FindType without problems.

Dardanus answered 15/5, 2012 at 20:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.