Re: dynamic object creation
- From: "Maarten Wiltink" <maarten@xxxxxxxxxxxxxxxxxx>
- Date: Thu, 27 Oct 2005 23:46:42 +0200
"B.r.K.o.N.j.A." <thebrkonja@xxxxxxx> wrote in message
news:djra9f$sd2$1@xxxxxxxxxxxxxxxxx
> Is there a way to do something similar to this?
>
> var classname: string;
> classname:='someclass';
> myclass:=<class contained in classname variable (someclass)> .create;
>
> I need to end up with myclass variable that holds reference to newly
> created someclass object.
>
> I can do classfactory class and do a lot of if-s but that's horrible
> solution, and I'm pretty sure there's a nice and clean solution to
> this one.
var
ClassRef: TComponentClass; { class of TComponent }
ObjRef: TComponent;
ClassRef:=TTreeView;
ObjRef:=ClassRef.Create(Owner);
There is one very big if about this. Unless you use a virtual
constructor, the declared type of ClassRef determines exactly
which constructor will be called.
var
ClassRef: TClass; { class of TObject }
ObjRef: TPersistent;
ClassRef:=TPersistent;
ObjRef:=ClassRef.Create;
This does not compile. The Create in TObject will be used, and it
does not return a TPersistent. Declaring ObjRef a TObject instead
will allow the code to compile, but the created object will still
be a TObject and not a TPersistent.
There is an alternative. You can compile a list of classes and
use a string for the "class reference", then check the string
against the ClassNames. There are prewritten functions
RegisterClass and GetClass that implement this. The drawback is
that each name can be used only once. There is no way to qualify
it with a unit name.
Conversely, the class reference/virtual constructor scheme ties
you to the virtual constructors in the base class. Adding parameters
halfway through the inheritance chain is not impossible, but
seriously messy and in any case you have to prepare for it at the
bottom.
Groetjes,
Maarten Wiltink
.
- Follow-Ups:
- Re: dynamic object creation
- From: B.r.K.o.N.j.A.
- Re: dynamic object creation
- References:
- dynamic object creation
- From: B.r.K.o.N.j.A.
- dynamic object creation
- Prev by Date: Re: dynamic object creation
- Next by Date: Re: dynamic object creation
- Previous by thread: Re: dynamic object creation
- Next by thread: Re: dynamic object creation
- Index(es):
Relevant Pages
|