How to convert class name to string to class?

I have class names in a string list. For example, it could be "TPlanEvent", "TParcel", "TCountry", etc.

Now I want to know the sizes, looping the list.

It works like this:

Size := TCountry.InstanceSize; 

But I want this:

 for i := 0 to ClassList.Count - 1 do Size := StringToClass(ClassList[i]).InstanceSize; 

Obviously my question is what to write instead of the StringToClass method to convert a string to a class.

+4
source share
4 answers

Since you are using a string list, you can also store classes:

 var C: TClass; StringList.AddObject(C.ClassName, TObject(C)); 

...

 for I := 0 to StringList.Count - 1 do Size := TClass(StringList.Objects[I]).InstanceSize; 

...

+10
source

If your classes are derived from TPersistent, you can use RegisterClass and FindClass or GetClass . Otherwise, you can write some kind of registration mechanism yourself.

+8
source

In Delphi 2010 you can use:

 function StringToClass(AName: string): TClass; var LCtx: TRttiContext; LTp: TRttiType; begin Result := nil; try LTp := LCtx.FindType(AClassName); except Exit; end; if (LTp <> nil) and (LTp is TRttiInstanceType) then Result := TRttiInstanceType(LTp).Metaclass; end; 

One note. Since you only save class names in a list, this method will not work because TRttiContext.FindType expects a fully qualified type name (for example, uMyUnit.TMyClass). The fix is ​​to attach the device where you store these classes in a loop or in a list.

+6
source
  • You must use FindClass to find a reference to the class by its name. If the class is not found, an exception will be raised.
  • If necessary, you should call RegisterClass for your classes, if they are not explicitly specified in the code.
+2
source

Source: https://habr.com/ru/post/1308213/


All Articles