Jack
Jack

Reputation: 31

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

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?

Upvotes: 2

Views: 207

Answers (4)

Richard Durr
Richard Durr

Reputation: 3271

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.

Upvotes: 0

akuhn
akuhn

Reputation: 27813

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.

Upvotes: 2

Germán Arduino
Germán Arduino

Reputation: 373

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.

Upvotes: 0

Germán Arduino
Germán Arduino

Reputation: 373

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.

Upvotes: 0

Related Questions