开发者

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

开发者 https://www.devze.com 2022-12-13 16:20 出处:网络
I\'ve seen thi开发者_StackOverflow中文版s recently and now I can\'t find it … How do you set the class of an object to something else?

I've seen thi开发者_StackOverflow中文版s 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?


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.


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号