How to create an class instance from a name of the class

Previous Topic Next Topic
 
classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

How to create an class instance from a name of the class

Sergei Gnezdov
How to create an instance of the class if this class is known by its
name in a String object?  In other words how to create objects
dynamically?

I found a somewhat indirect solution which uses dictionary:

        (dictionary at: 'ClassName') new.


Thank you


Reply | Threaded
Open this post in threaded view
|

Re: How to create an class instance from a name of the class

Bill Schwab-2
Sergei,

Try something like

    ( Smalltalk at:aClassName asSymbol ) new.

The important part is the #asSymbol, because the system dictionary
(Smalltalk is a global variable pointing to it) uses symbols for keys.

Some general precautions: use care in manipulating the system dictionary,
and/or keep very good backups :)  Using it to look up classes by name should
be safe enough though, as long as you don't do anything bad to the classes
that you find.  Note that some classes are singletons, and might complain;
even worse, they might not complain when they should.

Have a good one,

Bill

--
Wilhelm K. Schwab, Ph.D.
[hidden email]