본문 바로가기
Delphi/클래스

RTTI를 이용한 런타임 속성 정보 접근

by MonoSoft 2025. 3. 31.
728x90
반응형

RTTI를 이용한 런타임 속성 정보 접근

 

 

델파이의 RTTI(Run-Time Type Information)를 활용하면 
클래스나 객체의 속성, 메서드, 타입 정보 등을 
런타임 중에 확인하고 동적으로 접근할 수 있습니다. 
이를 통해 설정 자동화, JSON 직렬화, ORM 등의 고급 기능을 구현할 수 있습니다.

uses
  System.Rtti, System.TypInfo, System.SysUtils;

type
  TPerson = class
  private
    FName: string;
    FAge: Integer;
  published
    property Name: string read FName write FName;
    property Age: Integer read FAge write FAge;
  end;

procedure ShowPublishedProperties(Obj: TObject);
var
  RttiCtx: TRttiContext;
  RttiType: TRttiType;
  Prop: TRttiProperty;
begin
  RttiCtx := TRttiContext.Create;
  try
    RttiType := RttiCtx.GetType(Obj.ClassType);
    for Prop in RttiType.GetProperties do
    begin
      if Prop.IsReadable then
        ShowMessage(Format('%s = %s', [Prop.Name, Prop.GetValue(Obj).ToString]));
    end;
  finally
    RttiCtx.Free;
  end;
end;

procedure TestRTTI;
var
  Person: TPerson;
begin
  Person := TPerson.Create;
  try
    Person.Name := '홍길동';
    Person.Age := 30;
    ShowPublishedProperties(Person);
  finally
    Person.Free;
  end;
end;

●System.Rtti를 통해 클래스의 published 프로퍼티에 런타임 중 접근 가능
●코드 생성 없이 자동화된 정보 접근을 구현할 수 있어 생산성 향상
●TRttiContext는 매번 생성 후 반드시 Free 해주는 것이 좋음

 

 

 

728x90
반응형

댓글