Recent

Author Topic: ClassName to TObject  (Read 5578 times)

DimProfi

  • Full Member
  • ***
  • Posts: 126
    • http://www.dimprofi.de
ClassName to TObject
« on: January 09, 2011, 10:48:16 am »
Is it possible to make a function which creates Objects of Class, which name is defined as string?

Code: [Select]
function CreateObject(_classname:string):TObject;
If don't than may be it's possible using TClass as function parameter?

It doesn't work in this form ("Exception: Invalid Type Cast"),
but shows a concept to understand.

Code: [Select]
function CreateObject(_class:TClass):TObject;
begin
  Result:=_class.Create();
end;

I would be satisfied with a solution for second variant.
« Last Edit: January 09, 2011, 11:16:57 am by dimprofi »
Lazarus 1.2/FPC 2.6.4 (x86/x86_64/win32/win64/Linux) :: Be smart - use predictable {$INTERFACES CORBA}! :)

Leledumbo

  • Hero Member
  • *****
  • Posts: 8835
  • Programming + Glam Metal + Tae Kwon Do = Me
Re: ClassName to TObject
« Reply #1 on: January 09, 2011, 10:52:10 am »
You can use Class Reference (scroll down a little).

DimProfi

  • Full Member
  • ***
  • Posts: 126
    • http://www.dimprofi.de
Re: ClassName to TObject
« Reply #2 on: January 09, 2011, 11:22:45 am »
It's seems to work correctly now - Thanks!   8-)

Here one Example for the others:

Code: [Select]
type
TProtoObjectClass=class of TProtoObject;

...

function CreateProtoObject(_class:TProtoObjectClass):TProtoObject;
begin
  Result:=_class.Create();
end;
Lazarus 1.2/FPC 2.6.4 (x86/x86_64/win32/win64/Linux) :: Be smart - use predictable {$INTERFACES CORBA}! :)

Imants

  • Full Member
  • ***
  • Posts: 198
Re: ClassName to TObject
« Reply #3 on: January 09, 2011, 05:10:34 pm »
You can create object from string.

Code: [Select]
TProtoObjectClass=class of TProtoObject;

...

function CreateObject(_class: string):TObject;
begin
  Result:=TProtoObjectClass(FindClass(_class)).Create();
end;

...

initialization
  RegisterClass(TProtoObject); // class must be registred

DimProfi

  • Full Member
  • ***
  • Posts: 126
    • http://www.dimprofi.de
Re: ClassName to TObject
« Reply #4 on: January 09, 2011, 09:23:41 pm »
Hey that's amazing - thanks!  :o
Lazarus 1.2/FPC 2.6.4 (x86/x86_64/win32/win64/Linux) :: Be smart - use predictable {$INTERFACES CORBA}! :)

 

TinyPortal © 2005-2018