TypInfoGetEnumName (Delphi)

From RAD Studio Code Examples
Jump to: navigation, search

Description

This example demonstrates the methods to retrieve run-time type information (RTTI) information using GetEnumName. This example prints useful information about any given type, including its name, size, kind, and subkind.

Code

type
  TGenericClass<T> = class(TList<T>)
    // TList is a class in System.Generics.Collections.
  public
    procedure PrintTypeInfo;
  end;


procedure TGenericClass<T>.PrintTypeInfo;
var
  Info: PTypeInfo;
  Data: PTypeData;
  KindName: String;
  SubName: String;
begin
  { Get type info for the "yet unknown type". }
  Info := System.TypeInfo(T);

  { There is no RTTI attached for some types, such as Records. }
  if Info <> nil then
  begin
    WriteLn('Type name: ' + Info^.Name);

    { Find out the name of an enum item from its ordinal value. }
    KindName := System.TypInfo.GetEnumName(System.TypeInfo(TTypeKind),
      Ord(Info^.Kind));

    WriteLn('Type kind: ' + KindName);

    Data := GetTypeData(Info);

    if Info^.Kind = tkInteger then
    begin
      { In the case of Integer, here is the actual subtype name. }
      SubName := System.TypInfo.GetEnumName(System.TypeInfo(TOrdType),
        Ord(Data^.OrdType));
      WriteLn('Integer kind: ' + SubName);
    end;

    if Info^.Kind = tkFloat then
    begin
      { In the case of Float, here is the actual subtype name. }
      SubName := System.TypInfo.GetEnumName(System.TypeInfo(TFloatType),
        Ord(Data^.FloatType));
      WriteLn('Float kind: ' + SubName);
    end;

    if Info^.Kind = tkDynArray then
    begin
      { Check out the element size. }
      WriteLn('Array element type name: ' + Data^.elType^^.Name);
      WriteLn('Array element type size: ' + IntToStr(Data^.elSize));
    end;

  end;
  WriteLn('Size of type: ' + IntToStr(SizeOf(T))+#13#10);
end;

var
  GenericString: TGenericClass<UnicodeString>;
  GenericByte: TGenericClass<Byte>;
  GenericDouble: TGenericClass<Double>;

begin
  { Prints type info for the String type. }

  GenericString := TGenericClass<UnicodeString>.Create;
  GenericString.PrintTypeInfo;

  { Prints type info for the Byte type. }
  GenericByte := TGenericClass<Byte>.Create;
  GenericByte.PrintTypeInfo;

  { Prints type info for the Double type. }
  GenericDouble := TGenericClass<Double>.Create;
  GenericDouble.PrintTypeInfo;

  { Read a line to see the results. }
  ReadLn;
{
Expected results are:

Type name: string
Type kind: tkUString
Size of type: 4

Type name: Byte
Type kind: tkInteger
Integer kind: otUByte
Size of type: 1

Type name: Double
Type kind: tkFloat
Float kind: ftDouble
Size of type: 8
}

Uses

See Also