Returning and using class types (reflection?)

Jan 1 2008 10:22 AM
Hi

I'd like to return a class type from a method call, then create an instance of that returned class. I'm guessing it's got something to do with reflection / the 'Type' object? Any help would be greatly appreciated!

In delphi you'd be able to do it as follows:

unit Unit2;

interface

type
  TEnum = (enString, enInteger);

  TClassType = class of TClass;

  TClass = class // base class type
    class function ReturnClassType(Enum : TEnum) : TClassType;
  end;

  TClass1 = class(TClass)
  public
    v : string;
  end;

  TClass2 = class(TClass)
  public
    v : integer;
  end;

  TTesterClass = class
  public
    procedure Test;
  end;

implementation

uses
  Dialogs;

{ TClass }

class function TClass.ReturnClassType(Enum: TEnum): TClassType;
begin
  case Enum of
    enString : result:=TClass1;
    enInteger : result:=TClass2;
  end;
end;

{ TTesterClass }

procedure TTesterClass.Test;
var
  ClassType : TClassType;
  ValuedClass : TClass;
begin
  ClassType := TClass.ReturnClassType(enInteger);
  ValuedClass := ClassType.Create;

  ShowMessage(ValuedClass.ClassName);  // <- returns "TClass2"
end;

end.


Answers (3)