views:

111

answers:

4

Hi, I've seen this recently and now I can't find it …

How do you set the class of an object to something else?

--Update: Well, in Pharo! Like:

d:=Object new. d setClass: Dictionary.

Only that it isn't actually setClass. How can you modify the class pointer of an object?

A: 

The method #setClass: is used in some specific contexts and with different implementations (Check it with the Method Finder).

Object has some helpers to conver the current object in other sort of, as for example #asOrderedCollection, because this last permit the operation:

asOrderedCollection
    "Answer an OrderedCollection with the receiver as its only element."

    ^ OrderedCollection with: self

HTH.

Germán Arduino
That's all really helpful, but I really want to change the class pointer of my object. Assume that the other class has the same layout (same inst variables, not indexable), that should be possible, shouldn't it?
Jack
A: 

ok, then you can try something as:

d := Object new.
e := Dictionary new.

d become: e.

But, please, try #become: with caution, because in lot of situations it break the image.

Germán Arduino
+2  A: 

There is #primitiveChangeClassTo:.

It requires that both original and target class have the same class layout. For some strange reason it expects an instance of the target class as parameter, which is however not used.

So you would do

d := Object new.
d primitiveChangeClassTo: Dictionary new.

however this fails, since dictionaries have two instance variables but plain objects have none.

If you are into meta-programming, you might also be interesting in using any object as a class. I used that in Protalk to realize a prototype based language that works directly on top of Smalltalk.

Adrian
A: 

Take a look at Class ClassBuilder. It creates the a new class, when you modify a class, and then switches the instances of the former to instances of the later. Therefor it should provide some method that does, what you ask for.

Richard Durr