Programming Question

Andres Valloud sqrmax at cvtci.com.ar
Fri Apr 9 08:30:27 UTC 1999


Hi.

> Here's one I'm having trouble figuring out...
> 
> I have an object of class String something like the following:
> 
>   className := 'OrderedCollection'
> 
> What I want to do is something like:
> 
>   newObject := (className asClass) new
> 
> Of course there is no such message as "asClass".  The problem
> is that I can find no way to cause newObject to become a new
> object of class OrderedCollection.  Basically, I've got a string
> object whose contents are the name of some class, and I need to be
> able to send class-side messages like "new" to whichever class
> is named in the string, but I can't seem to find a mechanism for
> doing this.

Try this. Classes' names are Symbols, which are a special kind of Strings with
the interesting property that they are unique. This means, if two Symbols are
equal then they're THE SAME symbol (= = ==, equal equals equal equal <G>). And
as they're unique, then you can use them to call classes. How's that? Classes
are global objects because there're in a very special object called Smalltalk.
This one is a Dictionary, and in fact it's the SystemDictionary. It holds, among
other things, the classes that correspond to each symbol (of the symbols that
are class names). Then, you can get the class of name aSymbol (or nil if no such
class) from the expression:

Smalltalk at: aSymbol ifAbsent: [ ]

Then:

newObject := (Smalltalk at: className asSymbol) new.

This will trigger an error if no class with name className asSymbol, but it does
what you want given that the class exists.

Andres.





More information about the Squeak-dev mailing list