Class References (Class of Type) in Delphi - ablealias/Delphi GitHub Wiki
Sometimes operations are performed on a class itself, rather than on instances of a class (that is, objects). This happens, for example, when you call a constructor method using a class reference. You can always refer to a specific class using its name, but sometimes it is necessary to declare variables or parameters that take classes as values, and in these situations you need class-reference types. A class-reference type, sometimes called a metaclass, is denoted by a construction of the form:
class of type
where type is any class type. The identifier type itself denotes a value whose type is class of type.
type TClass = class of TObject;
var AnyObj: TClass;
declares a variable called AnyObj that can hold a reference to any class. You can assign the value nil to a variable of any class-reference type.
type TCollectionItemClass = class of TCollectionItem; ...
TCollection = class(TPersistent) ...
constructor Create(ItemClass: TCollectionItemClass);
A constructor can be called using a variable of a class-reference type. This allows construction of objects whose type isn't known at compile time. For example:
type TControlClass = class of TControl;
function CreateControl(ControlClass: TControlClass;
const ControlName: string; X, Y, W, H: Integer): TControl;
begin
Result := ControlClass.Create(MainForm);
with Result do
begin
Parent := MainForm;
Name := ControlName;
SetBounds(X, Y, W, H);
Visible := True;
end;
end;