2

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?

1
  • uh... could you elaborate slightly more?
    – Macke
    Commented Dec 3, 2009 at 20:29

4 Answers 4

2

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.

0

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.

1
  • 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
    Commented Dec 4, 2009 at 14:07
0

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.

1
  • become: is cool/weird/fun. But it doesn't do what the OP asked.
    – Dave Mason
    Commented Dec 9, 2012 at 14:38
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.